Various Ways to Measure Code Execution Time in Java
This article explains several common techniques for measuring Java code execution time, including System.currentTimeMillis(), Spring's StopWatch utility, System.nanoTime(), and the use of new Date(), providing code examples and a brief overview of StopWatch's API for developers seeking precise performance metrics.
In this article, the author discusses several common ways to measure code execution time in Java, starting with the simple use of System.currentTimeMillis() and moving to more precise utilities.
First, Spring's StopWatch class is introduced, with example code showing how to start, stop, and retrieve the total time in milliseconds.
StopWatch stopWatch = new StopWatch();
stopWatch.start();
//doInsert();
stopWatch.stop();
System.out.println(stopWatch.getTotalTimeMillis());Next, the native System.nanoTime() method is presented, including a code snippet that records start and end timestamps and prints the elapsed nanoseconds.
long startTime = System.nanoTime();
//doInsert();
long endTime = System.nanoTime();
System.out.println(endTime - startTime);The article also mentions using new Date() to obtain timestamps, with a corresponding example.
Date startDate = new Date();
//doInsert();
Date endDate = new Date();
System.out.println(endDate.getTime() - startDate.getTime());Although System.currentTimeMillis() is briefly noted, the focus remains on the three methods above.
A brief list of useful StopWatch methods (start, stop, isRunning, getTotalTimeMillis, getTotalTimeSeconds, getLastTaskTimeMillis, getTaskCount, prettyPrint, getTaskInfo) is provided for further exploration.
The author encourages readers to experiment, share thoughts, and join related discussion groups.
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.