How to find time taken to run a Java program?

Viewed 94191

I have a Java application that I've been working on and I just realized that the program has to return a value in less than a minute, but don't know how to find or display the time taken to run the program. How to find time taken to run a program?

7 Answers

You can use 2 APIs provided by System class

  1. System.currentTimeMillis() If code takes time in Millisecond range
  2. System.nanoTime() If code takes time in Nanosecond range

Sample Code

public class TestTimeTaken {
    public static void main(String args[]) throws InterruptedException{
        long startTimeNanoSecond = System.nanoTime();
        long startTimeMilliSecond = System.currentTimeMillis();

        //code
        Thread.sleep(1000);
        //code

        long endTimeNanoSecond = System.nanoTime();
        long endTimeMilliSecond = System.currentTimeMillis();

        System.out.println("Time Taken in "+(endTimeNanoSecond - startTimeNanoSecond) + " ns");
        System.out.println("Time Taken in "+(endTimeMilliSecond - startTimeMilliSecond) + " ms");


    }
}

I like using the Apache Commons StopWatch class when I have the library available.

import org.apache.commons.lang3.time.StopWatch;

// ...

StopWatch stopWatch = new StopWatch();
String message = "Task : %s (%s) seconds";

// ...

stopWatch.split();
System.out.println(String.format(message, "10", stopWatch.toSplitString()));

// ...

stopWatch.split();
System.out.println(String.format(message, "20", stopWatch.toSplitString()));

stopWatch.stop();

Related