How do I measure time elapsed in Java?
For precise nanosecond timing, use System.nanoTime():
For general millisecond timing, use System.currentTimeMillis():
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.
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.
Was this article helpful?