Measure execution time for a Java method

ID : 10280

viewed : 23

Tags : javajava

Top 5 Answer for Measure execution time for a Java method

vote vote


To be more precise, I would use nanoTime() method rather than currentTimeMillis():

long startTime = System.nanoTime(); myCall();  long stopTime = System.nanoTime(); System.out.println(stopTime - startTime); 

In Java 8 (output format is ISO-8601):

Instant start =; Thread.sleep(63553); Instant end =; System.out.println(Duration.between(start, end)); // prints PT1M3.553S 

Guava Stopwatch:

Stopwatch stopwatch = Stopwatch.createStarted(); myCall(); stopwatch.stop(); // optional System.out.println("Time elapsed: "+ stopwatch.elapsed(TimeUnit.MILLISECONDS)); 
vote vote


You can take timestamp snapshots before and after, then repeat the experiments several times to average to results. There are also profilers that can do this for you.

From "Java Platform Performance: Strategies and Tactics" book:

With System.currentTimeMillis()

class TimeTest1 {    public static void main(String[] args) {        long startTime = System.currentTimeMillis();        long total = 0;       for (int i = 0; i < 10000000; i++) {          total += i;       }        long stopTime = System.currentTimeMillis();       long elapsedTime = stopTime - startTime;       System.out.println(elapsedTime);    } } 

With a StopWatch class

You can use this StopWatch class, and call start() and stop before and after the method.

class TimeTest2 {    public static void main(String[] args) {        Stopwatch timer = new Stopwatch().start();        long total = 0;       for (int i = 0; i < 10000000; i++) {          total += i;       }        timer.stop();       System.out.println(timer.getElapsedTime());    } } 

See here (archived).

NetBeans Profiler:

Application Performance Application

Performance profiles method-level CPU performance (execution time). You can choose to profile the entire application or a part of the application.

See here.

vote vote


Check this: System.currentTimeMillis.

With this you can calculate the time of your method by doing:

long start = System.currentTimeMillis(); class.method(); long time = System.currentTimeMillis() - start; 
vote vote


In case you develop applications for Android you should try out the TimingLogger class.
Take a look at these articles describing the usage of the TimingLogger helper class:

vote vote


You might want to think about aspect-oriented programming. You don't want to litter your code with timings. You want to be able to turn them off and on declaratively.

If you use Spring, take a look at their MethodInterceptor class.

Top 3 video Explaining Measure execution time for a Java method