Monday, 29 July 2019

How to measure time taken by Java 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.

No comments:

Post a Comment