我正在编写一个程序来对我的磁盘进行基准测试。我计算了写入文件和从磁盘上的文件读取所需的时间。
我的 file_read 函数如下所示:
def read(blockSize): #blockSize is in bytes, varies from 1 byte, 1 KB and 1 MB
loops = 1048576 * fileSize / blockSize #number of iterations, fileSize is 100 (Mb)
fp = open("foo.txt", "r")
for j in xrange(0, loops):
fp.read(blockSize)
fp.close()
我计算的吞吐量非常高(接近 2 Gbps)。我怀疑这是因为文件存储在我的高速缓存中。有没有一种方法可以清除它以有效地对我的磁盘进行基准测试?
请您参考如下方法:
在 Linux 上,you can explicitly write to a special file to force the page cache to be cleared .
要用 Python 来做(因为运行一个程序来做它也会花费很多),你会做:
# On Python 3.3+, you can force a sync to disk first, minimizing the amount of
# dirty pages to drop as much as possible:
os.sync()
with open('/proc/sys/vm/drop_caches', 'w') as f:
f.write("1\n")
确保您在执行此操作时没有持有文件的打开句柄;文件的打开句柄可能会阻止其缓存被删除。
另一种可行的方法是使用 posix_fadvise 欺骗系统,以便它为您删除页面;您需要进行测试以确认,但您可以执行以下操作:
def read(blockSize): #blockSize is in bytes, varies from 1 byte, 1 KB and 1 MB
loops = 1048576 * fileSize / blockSize #number of iterations, fileSize is 100 (Mb)
with open("foo.txt") as fp:
# Lies to OS to tell it we won't need any of the data
os.posix_fadvise(fp.fileno(), 0, fileSize, os.POSIX_FADV_DONTNEED)
# Changed our mind! Read it fresh
os.posix_fadvise(fp.fileno(), 0, fileSize, os.POSIX_FADV_NORMAL)
for j in xrange(loops):
fp.read(blockSize)
与 os.sync 一样,Python API 直到 3.3 才引入,因此您需要在早期版本上使用 ctypes 滚动您自己的访问器。另请注意,如所写,您的代码永远不会回到文件的开头,而是读取比文件包含的数据多得多的数据。你是不是想回到最初?在每次寻求返回之前,您都需要重新提出建议。
