Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>If you want to measure the execution time of a method, you could also use the <code>System.nanoTime()</code> method of Java. Which uses the highest resolution timer available on your platform. The time is a relative 'free running time' which can only be compared with other nanoTime values. (<a href="https://blogs.oracle.com/dholmes/entry/inside_the_hotspot_vm_clocks" rel="nofollow">https://blogs.oracle.com/dholmes/entry/inside_the_hotspot_vm_clocks</a>)</p> <p>It is however very important to keep in mind that Java needs a significant time to "warm up". Java runs its compiled bytecode in the JVM (Java Virtual Machine) and uses its JIT (Just In Time compiler) to optimize parts of the bytecode at runtime to increase performance.</p> <p>If you want to have accurate measurements about execution speed, you should run your function several times, and do not use the measured times of the first runs. Take for instance the following code:</p> <pre><code>import java.util.Random; import tools.Helpers; public class DivideInlineShort { public static void main(String[] args) { int n = args.length &gt; 0 ? Integer.parseInt(args[0]) : 10000; Random r = new Random(); for (int i = 0; i &lt; 50; i++) runTest(n, r.nextInt(8) + 1); // you need the random to prevent the JVM removing the loops } public static void runTest(int n, int ran) { int counter = 0; long timeStart = System.nanoTime(); for (int j = 0; j &lt; n; j++) for (int i = ran; i &lt; 100000 + ran; i++) counter += return1(i); long timeEnd = System.nanoTime(); System.out.println( Helpers.roundedTimeInMillis(timeStart, timeEnd) + "\t\t" + counter); } public static int return1(int i) { return i / i; } } </code></pre> <p>The first 2 to 3 runs took my machine about 700ms, while the remaining 47 were around 370ms. This could be explained because of the inlining optimization which kicks in after a method is called more then 10.000 times if I remember correctly.</p> <p>So if you want an accurate measurement of the execution time of your code, you should run it multiple times on the same JVM instance and neglect the first few rounds.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload