0

I'm trying to benchmark how fast or slow it would take to save a binary file from one location to another.

    FileInputStream fis = new FileInputStream("/path/to/binary/file");
    BufferedInputStream in = new BufferedInputStream(fis);

    FileOutputStream fos = new FileOutputStream("/path/to/save/new/binary/file");
    BufferedOutputStream out = new BufferedOutputStream(fos);

    long before = System.currentTimeMillis();
    int data = 0;

    while ((data = in.read()) != -1) {
        out.write(data);
    }

    in.close();
    out.close();

    int seconds = (int) (System.currentTimeMillis() - before / 1000) % 60;

    System.out.println("Took " + seconds);

Buffered or unbuffered, the output is anywhere from 3 to 64 ms. I would have expected a closer range, say 40-50 or 10-20, or 30-40. What's the cause of this high fluctuation?

2 Answers 2

2

You can't expect consistency in your results by running only a single test, especially if it involves system calls and file I/O.

Improve the meaningfulness of your measurements by taking the following steps.

1
  • using nanoTime gives me the same result as with currentTimeMillis. So I'll have to run multiple tests and get the average from there. Feb 16, 2012 at 19:03
0

File I/O can have a lot of "randomness" involved:

  • This is a system call, so you're basically waiting until the IO scheduler decides to deal with your request
  • It may be on the hard drive, which takes time to read from
  • It may be cached in memory, which is fast(er)
  • Some other process may be doing heavy I/O
  • Some other process may be monopolizing the CPU

Look at cheeken's suggestions for how to deal with this.

2
  • 2
    It could be Tuesday, the moon could be waning, the ice cream truck may be driving down the street. All of these seem to affect micro benchmarks. And never, EVER, run tests on Feb. 29. They can only be duplicated once every 4 years. It's just unthoughtful to others trying to duplicate the work. Feb 16, 2012 at 18:26
  • The thing about Feb 29 is just an old wives tale. Experienced programmers know that to get optimal performance keep your system clock perpetually set to Feb 29 :)
    – emory
    Feb 16, 2012 at 19:30

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.