为什么在再次读取文件时读取文件更快? [英] Why file read is faster on reading again?

查看:140
本文介绍了为什么在再次读取文件时读取文件更快?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

SIZE = 1<<16
def justread(file):
    with open(file, 'rb') as f:
        while f.read(SIZE):
            pass

我第一次在700MB文件上运行此功能花了19秒. 当我重复
重新读取同一文件所需的时间降至0.5秒.
我重复了很多文件,结果很相似.
这是怎么回事?

The first time I run this function on a 700MB file it took 19 secs. When I repeated
reading the same file again the time it took dropped to 0.5secs.
I repeated this with many files and the results were similar.
What is going on here?

推荐答案

操作系统缓存第一次读取时在内存中的文件,第二次从内存而不是从硬盘读取文件.当然,内存要快得多.

The operating system caches the file in memory upon the first read, and the second time it is read from memory instead of from hard disk. Of course memory is much faster.

这篇关于为什么在再次读取文件时读取文件更快?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆