How do I calculate the time taken for the execution of a method in Java?
The now() method of the Instant class returns the current time and the Duration. between() methods returns the difference between the given two time values to get the elapsed time retrieve the time values before and after the execution of the desired method and retrieve the duration using the Duration.
The difference between the end time and start time is the execution time. Get the execution time by subtracting the start time from the end time.
To compute the elapsed time of an operation in seconds in Java, we use the System. currentTimeMillis() method.
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 = Instant.now(); Thread.sleep(63553); Instant end = Instant.now(); 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));
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.
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).
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With