Mastering Task Execution Timing in Java: From Date to Spring StopWatch
This guide compares simple Date‑based timing, System.currentTimeMillis(), and Spring's StopWatch utility, showing how to accurately measure and analyze execution durations of individual code blocks in Java applications.
When profiling code performance or diagnosing runtime issues, accurately measuring task execution time is essential. The simplest approach prints the difference between the current time and a recorded start time, often using new Date().getTime():
@Test
public void testElapsedTimes() throws InterruptedException {
long startTime = new Date().getTime();
// do something
Thread.sleep(1000);
System.out.println("执行耗时:" + (new Date().getTime() - startTime) + "ms");
}While straightforward, this method becomes cumbersome when many test blocks require timing. IDE inspections usually recommend System.currentTimeMillis() for a lighter-weight timestamp:
@Test
public void testElapsedTimes1() throws InterruptedException {
long startTime = System.currentTimeMillis();
// do something
Thread.sleep(1000);
System.out.println("执行耗时:" + (System.currentTimeMillis() - startTime) + "ms");
}Both approaches ultimately call System.currentTimeMillis()</b> inside the <code>Date constructor, so using the direct method avoids unnecessary object creation and improves performance.
Spring's StopWatch Utility
Spring provides the org.springframework.util.StopWatch class, which encapsulates start/stop timing and offers richer reporting. A basic usage example:
@Test
public void testStopWatch() throws InterruptedException {
StopWatch sw = new StopWatch();
sw.start("开始执行业务");
// do something
Thread.sleep(1000);
sw.stop();
System.out.println(sw.getTotalTimeMillis());
}For more complex scenarios, multiple named tasks can be timed sequentially:
@Test
public void testStopWatch1() throws InterruptedException {
StopWatch sw = new StopWatch();
sw.start("起床");
Thread.sleep(1000);
sw.stop();
sw.start("洗漱");
Thread.sleep(2000);
sw.stop();
sw.start("锁门");
Thread.sleep(500);
sw.stop();
System.out.println(sw.prettyPrint());
System.out.println(sw.getTotalTimeMillis());
System.out.println(sw.getLastTaskName());
System.out.println(sw.getLastTaskInfo());
System.out.println(sw.getTaskCount());
}The output shows each task's duration, percentage of total time, and overall statistics, demonstrating the utility's ability to provide detailed performance insight.
Separate multiple code blocks with distinct start / stop calls.
Name each task via the start(String taskName) argument.
Access total time, per‑task time, and task count for analysis.
Use prettyPrint() for a formatted summary.
Retrieve the last task name or full TaskInfo for further processing.
Implementation Details
The StopWatch.start() method records the task name and the start timestamp using System.nanoTime():
public void start(String taskName) throws IllegalStateException {
if (this.currentTaskName != null) {
throw new IllegalStateException("Can't start StopWatch: it's already running");
}
this.currentTaskName = taskName;
this.startTimeNanos = System.nanoTime();
}The stop() method calculates the elapsed nanoseconds, updates total time, stores task info, and optionally keeps a task list:
public void stop() throws IllegalStateException {
if (this.currentTaskName == null) {
throw new IllegalStateException("Can't stop StopWatch: it's not running");
}
long lastTime = System.nanoTime() - this.startTimeNanos;
this.totalTimeNanos += lastTime;
this.lastTaskInfo = new TaskInfo(this.currentTaskName, lastTime);
if (this.keepTaskList) {
this.taskList.add(this.lastTaskInfo);
}
++this.taskCount;
this.currentTaskName = null;
}Other getter methods simply format or return the collected timing data.
Conclusion
While simple timestamp subtraction works, Spring's StopWatch offers a structured, extensible way to profile multiple sections of code, providing clear, formatted reports and easy access to detailed metrics, making it a valuable tool for backend developers seeking precise performance insights.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
Senior Brother's Insights
A public account focused on workplace, career growth, team management, and self-improvement. The author is the writer of books including 'SpringBoot Technology Insider' and 'Drools 8 Rule Engine: Core Technology and Practice'.
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.
