Why file read is faster on reading again?

后端 未结 2 690
青春惊慌失措
青春惊慌失措 2021-01-07 04:38

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

The first time I run t

相关标签:
2条回答
  • 2021-01-07 05:43

    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.

    0 讨论(0)
  • 2021-01-07 05:43

    Your operating system is caching the file.

    What? This means, the first time you read the file, your program had to go look for the information in the hard drive, and hard drives are slooooow.

    Now, after having read the whole file for the first time, Linux kept it around in memory just in case, and probably because there was nothing important to have instead at the time. So, the second time you read it, you were accessing the copy in memory, without reaching for the hard drive, which is orders of magnitude faster.

    Cheers!

    0 讨论(0)
提交回复
热议问题