This question already has an answer here:
I need to analyze complexity for some algorithms in Java. For that I am planning to give large number of input and measure the time taken by Java implementation. What is the most precise and accurate way to check time between some lines of code? I need precision in milliseconds...
You can get nanosecond resolution, even, using System.nanoTime()
.
However, you may want to consider the points in the following:
How do I write a correct micro-benchmark in Java?
Use a library such as Speed4j. This shall not only benchmark the calls but also provide statistics in logs, also you can see them remotely via JMX. It is better of using such a library rather than placing System.current.. calls all over the code.
Say you have a particular method that you would like to put under the microscope. You can do that as follows:
long time1 = System.nanoTime();
thatMethod();
long time2 = System.nanoTime();
long timeTaken = time2 - time1;
System.out.println("Time taken " + timeTaken + " ns");
Computers are really fast so it may happen that time difference when using getTimeMillis()
maybe zero. Hence, use nanoTime()
You can also use Caliper
. They have a video to get started. Plus, thoroughly read the answer pointed to by creichen
. It has a lot of great stuff in it.
Use System.nanoTime()
or System.currentTimeMillis()
to get both start and finish time of your code. Be aware that micro-benchmarks measure only basic aspects of JVM performance. Be aware of warm up phase for JVM, after which JIT is started.
long start = System.currentTimeMillis();
// your code
long end = System.currentTimeMillis();
long diff = end-start;
or
long start = System.nanoTime();
// your code
long end = System.nanoTime();
long diff = end-start;
long diffInMillis = diff/1000000;
long startTime = System.currentTimeMillis();
//code lines whose time you want to calculate
long endTime = System.currentTimeMillis();
System.out.println("Took "+(endTime - startTime) + " ms");
-1
this but then.. please format your code. Avoid stating what has already been stated. - Little Child