Why first-time reading file from hdd is slower then next ones?

0

I am measuring my HDD speed with a self-written program. (This is a sort of homework, so I don't need recommendations about existing tools to do that).

I do it with the following piece of code:

    for(int attemptNumber =0; attemptNumber < ATTEMPTS; attemptNumber++) {

        long start = System.currentTimeMillis();
        BufferedReader bf = new BufferedReader(new FileReader(FILENAME));
        int c = 0;
        while((c = bf.read()) != -1) {

        }
        long end = System.currentTimeMillis();
        System.out.println(end - start);
    }

In the output the first number is usually 3 times larger then any of the next:

14234
5130
4859
... etc

When I restart the application, I get the same results: first read is ~3 times slower. Why is this happening?

EDIT: I'm not sure if this is the right SO site to ask, where should I post this?

Ilya Smagin

Posted 2014-09-18T10:21:50.897

Reputation: 103

Answers

2

Most operating systems and some hardware as well maintain a disk cache. The first read is from the actual disk and slow, but subsequent reads come from the faster cache .

HBruijn

Posted 2014-09-18T10:21:50.897

Reputation: 1 024