Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/278.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/jpa/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 如何清除我的缓存?_Python - Fatal编程技术网

Python 如何清除我的缓存?

Python 如何清除我的缓存?,python,Python,我正在编写一个程序来对我的磁盘进行基准测试。我计算写入文件和读取磁盘上文件所需的时间 我的文件读取函数如下所示: 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

我正在编写一个程序来对我的磁盘进行基准测试。我计算写入文件和读取磁盘上文件所需的时间

我的文件读取函数如下所示:

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上

要在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
来滚动自己的访问器。还要注意的是,在编写时,您的代码从不返回到文件的开头,而是读取比文件包含的数据多得多的数据。你是不是想从头再来?您需要在每次回访前重新提出建议