score:80

Accepted answer

You can compare times using System.nanoTime() . It will return the time in nanoseconds.

Returns the current value of the most precise available system timer, in nanoseconds.

You could use it like this:

long startTime = System.nanoTime();

// code

long endTime = System.nanoTime();
System.out.println("Took "+(endTime - startTime) + " ns"); 

Usefull links:

score:0

This is a typical usecase for aspects, for example using Spring AOP:

@Aspect
public class TimerAspect {

    private static final Logger LOG = Logger.getLogger(TimerAspect.class);

    @Around("com.xyz.myapp.MyClass.myMethod()")
    public Object doBasicProfiling(ProceedingJoinPoint pjp) throws Throwable {
        long startTime = System.nanoTime();
        Object retVal = pjp.proceed();
        long endTime = System.nanoTime();
        LOG.info(String.format("Call to %s.%s with args %s took %s ns", pjp.getTarget(), pjp.getSignature(), Arrays.toString(pjp.getArgs()), endTime - startTime));
        return retVal;
    }
}

And in your application context:

<aop:aspectj-autoproxy/>
<bean id="myAspect" class="org.xyz.TimerAspect"/>   

score:1

If you just want to know how long does your program run use System.currentTimeMillis() in the beginning and end of your program.

score:1

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();

score:2

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");


    }
}

score:3

If you have Spring as a dependency of your project (or don't mind adding it), you can use StopWatch. As the name suggests, once initialized it will count the time until you stop it. You can then check the time taken for a task. Multiple StopWatches can be used simultaneously to multiple tasks keeping the code clean.

Besides keeping your code clean, StopWatches help with formatting the time and other utility methods.

public void myMethod(){
    StopWatch stopWatch = new StopWatch();

    stopWatch.start("Task1");
    // ...
    // Do my thing
    // ...
    stopWatch.stop();
    System.out.println("Task executed in " + stopWatch.getTotalTimeSeconds() + "s");
}

score:15

There is no built-in way to see for how long your program has been running. However, you could at the start of the program just store the current time, so that sometime later you can see how much time has elapsed.

public class MyProgram {
    private static long startTime = System.currentTimeMillis();

    public static void main(String[] args) {
        // Do stuff...

        // At the end
        long endTime = System.currentTimeMillis();
        System.out.println("It took " + (endTime - startTime) + " milliseconds");
    }
}

Related Query

More Query from same tag