1

I'm trying to calculate the amount of time a single iteration takes in a for loop I've written that writes lines to a file in Java. After looking around, it seems like one method that people use to do this is by grabbing the System time at the beginning and end of the execution and subtracting those results. Here's what I have in my code:

String content;
for (int i = 0 ; i < 100; i += 1 ) {
    long startTime = System.nanoTime();
    content = "Currently writing line " + i " to the file.";
    myBufferedWriter.write(content);
    long endTime = System.nanoTime();
    System.out.println("This iteration took: " + (endTime - startTime) " time.");
}

However, looking at my results I get mostly something like this:

This iteration took: 1000 time
This iteration took: 1000 time
This iteration took:    0 time
This iteration took: 1000 time
...
This iteration took: 24000 time
This iteration took: 1000 time
This iteration took:    0 time
This iteration took: 17000 time

So on and so forth. Essentially most of the iterations look like they execute with a similar speed, but why exactly is there that crazy fluctuation in both ends of the spectrum at times? Sometimes it ends up going really quickly (no difference in time?) and sometimes it takes a lot longer. What gives?

Jeff Gong
  • 1,713
  • 3
  • 15
  • 19
  • 1
    Do the lines you're writing vary greatly in length? – DigitalNinja Jun 23 '15 at 00:28
  • 2
    Can you post your complete example? It's almost complete. You're just missing the declaration of your `myBufferedWriter`. That way we can run it as well. As it stands, even the snippet you provided doesn't compile, there are a few mistakes in it. Providing a small reproduceable program will be very useful. – sstan Jun 23 '15 at 00:40
  • 2
    Take a look at [Micro-benchmark in Java](http://stackoverflow.com/questions/504103/how-do-i-write-a-correct-micro-benchmark-in-java). It could be due to garbage collection (The sudden increase in time). – almightyGOSU Jun 23 '15 at 00:46
  • 2
    Actually, I just realized that your measurements are in nanoseconds. Having fluctuations while doing I/O work is completely normal. And the value differences between your measurements is so minuscule, that you could say that it ran pretty consistently I would say. – sstan Jun 23 '15 at 00:49
  • @DigitalNinja the lines are all of the same length with the only thing changing being which number is placed into the string based on the current iteration. – Jeff Gong Jun 23 '15 at 00:52
  • @sstan thanks for the help! I'm going to go ahead and assume that this is pretty normal then. I'll edit the post in just a little later with my bufferedWriter implementation if that's helpful. – Jeff Gong Jun 23 '15 at 00:53
  • Measuring time is better done with a stopwatch... (Class not physical object) – D. Ben Knoble Jun 23 '15 at 01:00

0 Answers0