Saturday, 17 December 2016

Measure Code Speed in Java

How to measure code speed in Java

Quite often we have two solutions in our mind and we don't know which one is the best to use.
Simple way to decide that is to measure speed for executing for both code versions and use one that is faster.

So how we can actually measure the code speed? In Java it is quite easy.

You will need to recognize few key points in your code, when does it starts and when does it ends.

Before beginning your code you will add something like this:
long startTime = System.nanoTime();
This will get the current system time and put it in one variable.

At the end of code you want to measure you need to put:
long totalExecutionTime = System.nanoTime() - startTime ;
This will get current system time at the end of the code and subtract start time we created at the start of the code.

In order to see how fast is it you can just print it to console:
System.out.println("Total execution time: " + (totalExecutionTime / 1000000.0) + " ms");
This code will get the result of subtraction and divide it with 1M, this is done only to get better representation of the result we have. After we divide that, we will print the result and add "ms" at the end that we now result is in milliseconds. 1000 ms is 1 sec.

So we now know how to check the speed of our code, in order to compare it with other code you will do the same for other part:
long startTime2 = System.nanoTime();
... (code you want to measure) ...

long totalExecutionTime2 = System.nanoTime() - startTime2 ;
System.out.println("Total execution time 2: " + (totalExecutionTime2 / 1000000.0) + " ms");

Instead of just printing values you can now compare them:
if ( totalExecutionTime > totalExecutionTime2 ) {
         System.out.println("First code is faster!");
} else if ( totalExecutionTime < totalExecutionTime2 ) {
          System.out.println("Second code is faster!"); 
} else {
          System.out.println("They are equally fast!"); 

You can check our code example where we compare String VS String builder using this speed test: String VS StringBuilder
If this little "code" helped you, please subscribe, like us on Facebook, share it and enjoy.

Kind regards,