sixtytrees sixtytrees - 4 months ago 18
Java Question

'Rule of a thumb' for cost of printing

I've noticed that

int i=10000000;
boolean isPrime= false;
while(!isPrime){
i++;
System.out.println(item); //this kills performance
isPrime = checkIfPrime(i);

}
}


Printing the current value of a variable kills performance. I want to print it once in a while, but keep the cost of this operation low.

How to compare the cost of printing to screen to computation? Are there any tricks to minimize this cost [Should I print one out of 10 records, or will this cost just as much because of conditional check]?




Why do I need this? Well, I am doing fun stuff with Java (such as "find a counterexample for Euler's conjuncture... 27^5 + 84^5 + 110^5 + 133^5 = 144^5 (Lander & Parkin, 1966),"). I want to write a program that is both correct and fast (this counterexample was discovered in 60s, so I should be able to do it in reasonable time). While debugging I want to have as much info and possible and I want to find the counterexample asap. What is my best way to proceed? Print each case? - Too slow. Let it run overnight? What if I missed some
i++
?

Answer

How to compare the cost of printing to screen to computation?

It is not possible. The cost (i.e elapsed time) of printing depends on where the "printed" characters go. I can trivially construct an example where the cost tends to infinity.

  $ java YourClass | ( sleep 10000000000 )

After a few lines of output, the pipeline buffers will fill, and the print calls in your application will block.

Are there any tricks to minimize this cost [Should I print one out of 10 records, or will this cost just as much because of conditional check]?

There is nothing that won't introduce another overhead; e.g. the overhead of testing whether or not to print.

The only way to entirely eliminate the print overhead is to not print at all while you are trying to measure performance.


What is my best way to proceed? Print each case? - Too slow. Let it run overnight? What if I missed some i++?

First run the program with the print statements to check that you are getting the right answers.

Then remove the print statements and run again to get your performance measures.

However:

  1. Beware of the various traps in writing Java micro-benchmarks.
  2. Trawling through pages and pages of trace prints is not a good way to check for (possible) faults in your program.