Explain Codes LogoExplain Codes Logo

How do I measure time elapsed in Java?

java
benchmarking
performance-tuning
java-time-classes
Nikita BarsukovbyNikita BarsukovยทNov 11, 2024
โšกTLDR

For precise nanosecond timing, use System.nanoTime():

long start = System.nanoTime(); // Somewhere here, your code is throwing a party ๐Ÿฅณ long elapsed = System.nanoTime() - start; System.out.println("After party cleaning time: " + elapsed + " ns");

For general millisecond timing, use System.currentTimeMillis():

long start = System.currentTimeMillis(); // Code here, procrastinating like a master ๐Ÿ˜Ž long elapsed = System.currentTimeMillis() - start; System.out.println("Procrastination time: " + elapsed + " ms");

Granularity in measuring time

When it comes to precision and accuracy, nanoTime beats currentTimeMillis. It provides high resolution and is perfect for benchmarking, sweating over every nanosecond.

Note that System.nanoTime() is a lone wolf unaffected by system's clock adjustments, making it rock-solid reliable for high-precision tracking. However, for the tracking events over long periods, or when actual wall-clock time matters, old System.currentTimeMillis() can still be your friend.

Third-party utilities and AspectJ

So you don't want to reinvent the wheel? Third-party solutions like Apache's Commons Lang StopWatch and Java Management Extensions (JAMon) offer cool tools to manage time, like a boss! It-Boy of Aspect-Oriented Programming (AOP), AspectJ in combination with JAMon can sample method execution time in a stealthy and non-intrusive way.

Even considering crafting a custom TimeWatch class? It can serve as a Swiss army knife for chronometry: flexible, reusable, featuring reset capabilities.

Nanosecond precision with Java time classes

Java 8 brought us the java.time framework, an atomic clock in your hands. Use Instant.now() to capture exact point-in-time in UTC, Duration.between() to calculate time intervals with nanosecond precision.

Instant start = Instant.now(); // ... Your code here playing hide and seek... Instant end = Instant.now(); Duration duration = Duration.between(start, end); System.out.println("Hide and seek time: " + duration.toNanos() + " ns");

With Duration, you can extract specific time units, and LocalTime is there for handling time-of-day calculations, being your reliable friend when crossing midnight.

Your best friend for debugging, Duration.toString(), gives you elapsed time in a friendly, cuddly ISO 8601 format.

Pro tip: java.time classes are superior to java.util.Date and Calendar, being time-zone-aware, robust and immutable.

AspectJ's MonitorAspect for method duration monitoring

MonitorAspect, AspectJ's star, monitors method durations, being your secret agent for tracing performance of your application.

Battle-tested StopWatch for multi-stage processes

Whenever there's a complex, multi-stage process, Apache's StopWatch hits the stage with its toSplitString() method. It delivers split timing checks, perfect for detailed logging or reporting.