Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to measure time taken by Java code? [duplicate]

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...

like image 660
Mangat Rai Modi Avatar asked Nov 26 '13 08:11

Mangat Rai Modi


People also ask

How do you measure time in Java?

The currentTimeMillis() method returns the current time in milliseconds. To find the elapsed time for a method you can get the difference between time values before and after the execution of the desired method. The nanoTime() method returns the current time in nano seconds.

How do you check how long a program has been running Java?

There are two ways to measure elapsed execution time in Java either by using System. currentTimeinMillis()or by using System. nanoTime(). These two methods can be used to measure elapsed or execution time between two method calls or events in Java.

How is code execution time calculated?

We can calculate the execution time of the code using StartNew() and Stop() methods. StartNew() method comes under the Stopwatch class and it basically used to initialize a new Stopwatch instance.


1 Answers

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?

like image 93
creichen Avatar answered Oct 20 '22 05:10

creichen