Various Ways to Measure Code Execution Time in Java
This article explains several Java techniques for measuring code execution time—including Spring's StopWatch, System.nanoTime, new Date, and System.currentTimeMillis—provides sample code snippets, discusses their usage and output, while also briefly mentions related utilities, and contains promotional links and community invitations.
In this article, a senior architect shares multiple approaches to measure the execution time of Java code, starting with a brief introduction that mentions the common use of System.currentTimeMillis() for simple timing.
StopWatch
The first method utilizes Spring's StopWatch utility. Example code:
StopWatch stopWatch = new StopWatch();
stopWatch.start();
//doInsert(); // execute business logic
stopWatch.stop();
System.out.println(stopWatch.getTotalTimeMillis());The output displays the total elapsed time in milliseconds.
System.nanoTime()
The second method uses System.nanoTime() for higher‑resolution timing. Example code:
long startTime = System.nanoTime();
doInsert(); // execute business logic
long endTime = System.nanoTime();
System.out.println(endTime - startTime);This prints the elapsed nanoseconds between the two calls.
new Date()
The third method employs new Date() objects. Example code:
Date startDate = new Date();
//doInsert(); // execute business logic
Date endDate = new Date();
System.out.println(endDate.getTime() - startDate.getTime());The difference of the two timestamps yields the duration in milliseconds.
System.currentTimeMillis()
The fourth method simply references System.currentTimeMillis() , which is similar to the new Date() approach and is omitted for brevity.
Additional information about the StopWatch API is listed, including methods such as start(String taskName) , stop() , isRunning() , getTotalTimeMillis() , getTotalTimeSeconds() , and others that provide detailed timing capabilities.
The article concludes with a reminder to explore the source code of StopWatch , which internally relies on System.nanoTime() , and encourages readers to discuss and share their thoughts.
Throughout the content, there are promotional sections inviting readers to join groups, claim gifts, and follow related links.
Top Architect
Top Architect focuses on sharing practical architecture knowledge, covering enterprise, system, website, large‑scale distributed, and high‑availability architectures, plus architecture adjustments using internet technologies. We welcome idea‑driven, sharing‑oriented architects to exchange and learn together.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.