如何清除我的缓存?

时间:2016-02-11 23:18:38

标签: python

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

我的file_read函数如下所示:

 // dynamically you can call
 String className = "mypackage.MyClass";
 String javaCode = "package mypackage;\n" +
                  "public class MyClass implements Runnable {\n" +
                  "    public void run() {\n" +
                  "        System.out.println(\"Hello World\");\n" +
                  "    }\n" +
                  "}\n";
 Class aClass = CompilerUtils.CACHED_COMPILER.loadFromJava(className, javaCode);
 Runnable runner = (Runnable) aClass.newInstance();
 runner.run();

我计算的吞吐量非常高(接近2 Gbps)。我怀疑这是因为文件存储在我的缓存中。有没有办法可以清除它以有效地对我的磁盘进行基准测试?

1 个答案:

答案 0 :(得分:2)

在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滚动自己的访问者。另请注意,编写时,您的代码永远不会回溯到文件的开头,但会读取比文件包含的数据多得多的数据。您是否意味着要回到起点?在每次回访之前,你需要重新提出建议。

相关问题