Why file read is faster on reading again?

后端 未结 2 691
青春惊慌失措
青春惊慌失措 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

    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!

提交回复
热议问题