4

I've got a simple program that I got from my Java programming book, just added a bit to it.

package personal;

public class SpeedTest {
  public static void main(String[] args) {
    double DELAY = 5000;
    long startTime = System.currentTimeMillis();
    long endTime = (long)(startTime + DELAY);
    long index = 0;

    while (true) {
      double x = Math.sqrt(index);
      long now = System.currentTimeMillis();
      if (now >= endTime) {
        break;
      }
      index++;
    }
    System.out.println(index + " loops in " + (DELAY / 1000) + " seconds.");
  }
}

This returns 128478180 loops in 5.0 seconds.

If I add System.out.println(x); before the if statement, then my number of loops in 5 seconds goes down to the 400,000s, is that due to latency in the System.out.println()? Or is it just that x was not being calculated when I wasn't printing it out?

Maroun
  • 94,125
  • 30
  • 188
  • 241
Kaelinator
  • 360
  • 3
  • 17
  • 8
    Printing to the console has got to be the worst thing you can do performance wise. IO operations takes a lot of time. – Tunaki Apr 25 '16 at 14:20
  • System.out.println is an IO operation and yes it can effect performance of any program – Sanjeev Apr 25 '16 at 14:21
  • 6
    Well asked question, I don't understand the downvotes. Just because it's a trivial one for you, doesn't mean you should downvote. – Maroun Apr 25 '16 at 14:22
  • 2
    For comparison purposes, you could use a `StringBuilder` and `append(x)` inside the loop, and then print it out .... – Stewart Apr 25 '16 at 14:23

1 Answers1

0

Anytime you "do output" within a very-busy loop, in any programming language whatsoever, you introduce two possibly-very-significant delays:

  1. The data must be converted to printable characters, then be written to whatever display/device it might be going to ... and ...
  2. "The act of outputting anything" obliges the process to synchronize itself with any-and-every-other process that might also be generating output.

One alternative strategy that is often used for this purpose is a "trace table." This is an in-memory array, of some fixed size, which contains strings. Entries are added to this table in a "round-robin" fashion: the oldest entry is continuously being replaced by the newest one. This strategy provides a history without requiring output. (The only requirement that remains is that anyone which is adding an entry to the table, or reading from it, must synchronize their activities e.g. using a mutex.)

Processes which wish to display the contents of the trace-table should grab the mutex, make an in-memory copy of the content-of-interest, then release the mutex before preparing their output. In this way, the various processes which are contributing entries to the trace-table will not be delayed by I/O-associated sources of delay.

Mike Robinson
  • 8,490
  • 5
  • 28
  • 41