How to time Java program execution speed
Be aware that there are some issues where System#nanoTime()
cannot be reliably used on multi-core CPU's to record elapsed time ... each core has maintains its own TSC (Time Stamp Counter): this counter is used to obtain the nano time (really it is the number of ticks since the CPU booted).
Hence, unless the OS does some TSC time warping to keep the cores in sync, then if a thread gets scheduled on one core when the initial time reading is taken, then switched to a different core, the relative time can sporadically appear to jump backwards and forwards.
I observed this some time ago on AMD/Solaris where elapsed times between two timing points were sometimes coming back as either negative values or unexpectedly large positive numbers. There was a Solaris kernel patch and a BIOS setting required to force the AMD PowerNow! off, which appeared to solved it.
Also, there is (AFAIK) a so-far unfixed bug when using java System#nanoTime()
in a VirtualBox environment; causing all sorts of bizarre intermittent threading problems for us as much of the java.util.concurrency
package relies on nano time.
See also:
Is System.nanoTime() completely useless? http://vbox.innotek.de/pipermail/vbox-trac/2010-January/135631.html
You get the current system time, in milliseconds:
final long startTime = System.currentTimeMillis();
Then you do what you're going to do:
for (int i = 0; i < length; i++) {
// Do something
}
Then you see how long it took:
final long elapsedTimeMillis = System.currentTimeMillis() - startTime;
final long startTime = System.currentTimeMillis();
for (int i = 0; i < length; i++) {
// Do something
}
final long endTime = System.currentTimeMillis();
System.out.println("Total execution time: " + (endTime - startTime));