Backend Development 11 min read

Using Spring and Apache Commons StopWatch for Precise Code Execution Timing in Java

This article explains why simple System.currentTimeMillis() timing is often insufficient, introduces Spring's org.springframework.util.StopWatch and Apache Commons' org.apache.commons.lang3.time.StopWatch, provides Maven dependencies and complete Java examples, and discusses important usage notes such as thread‑safety and task management.

Java Architect Essentials
Java Architect Essentials
Java Architect Essentials
Using Spring and Apache Commons StopWatch for Precise Code Execution Timing in Java

When measuring the execution time of a piece of code, many developers simply record the start and end timestamps with System.currentTimeMillis() , but this approach quickly becomes cumbersome for multiple tasks or when more detailed reporting is required.

To address these limitations, two ready‑made timer utilities are commonly used in Java projects: Spring's StopWatch (in org.springframework.util ) and Apache Commons Lang3 StopWatch (in org.apache.commons.lang3.time ). Both provide convenient APIs for starting, stopping, splitting, and summarising task durations.

Spring StopWatch usage

First, add the Spring core dependency (already included in Spring Boot projects):

<!-- https://mvnrepository.com/artifact/org.springframework/spring-core -->
org.springframework
spring-core
${spring.version}

Example code:

public static void main(String[] args) throws InterruptedException {
    StopWatch stopWatch = new StopWatch();

    // Task 1 – simulate 3‑second sleep
    stopWatch.start("TaskOneName");
    Thread.sleep(1000 * 3);
    System.out.println("当前任务名称:" + stopWatch.currentTaskName());
    stopWatch.stop();

    // Task 2 – simulate 10‑second sleep
    stopWatch.start("TaskTwoName");
    Thread.sleep(1000 * 10);
    System.out.println("当前任务名称:" + stopWatch.currentTaskName());
    stopWatch.stop();

    // Task 3 – another 10‑second sleep
    stopWatch.start("TaskThreeName");
    Thread.sleep(1000 * 10);
    System.out.println("当前任务名称:" + stopWatch.currentTaskName());
    stopWatch.stop();

    // Print detailed report and short summary
    System.out.println(stopWatch.prettyPrint());
    System.out.println(stopWatch.shortSummary());

    // Access last task information
    System.out.println(stopWatch.getLastTaskName());
    System.out.println(stopWatch.getLastTaskInfo());

    // Total time and task count
    System.out.println("所有任务总耗时:" + stopWatch.getTotalTimeMillis());
    System.out.println("任务总数:" + stopWatch.getTaskCount());
    System.out.println("所有任务详情:" + stopWatch.getTaskInfo());
}

Apache Commons StopWatch usage

Add the Commons Lang3 dependency:

<!-- https://mvnrepository.com/artifact/org.apache.commons/commons-lang3 -->
org.apache.commons
commons-lang3
3.6

Example code demonstrating start, split, reset, suspend/resume and conversion to seconds:

public static void main(String[] args) throws InterruptedException {
    StopWatch watch = StopWatch.createStarted();
    Thread.sleep(1000);
    System.out.println(watch.getTime());
    System.out.println("统计从开始到现在运行时间:" + watch.getTime() + "ms");

    Thread.sleep(1000);
    watch.split();
    System.out.println("从start到此刻为止的时间:" + watch.getTime());
    System.out.println("从开始到第一个切入点运行时间:" + watch.getSplitTime());

    Thread.sleep(1000);
    watch.split();
    System.out.println("从开始到第二个切入点运行时间:" + watch.getSplitTime());

    // Reset and start a new measurement
    watch.reset();
    watch.start();
    Thread.sleep(1000);
    System.out.println("重新开始后到当前运行时间是:" + watch.getTime());

    // Suspend and resume
    watch.suspend();
    System.out.println("暂停2秒钟");
    Thread.sleep(2000);
    watch.resume();
    System.out.println("恢复后执行的时间是:" + watch.getTime());

    Thread.sleep(1000);
    watch.stop();
    System.out.println("花费的时间》》" + watch.getTime() + "ms");
    System.out.println("花费的时间》》" + watch.getTime(TimeUnit.SECONDS) + "s");
}

Important notes

Both StopWatch implementations are not thread‑safe; they should be used in a single‑threaded context or with external synchronization.

A StopWatch instance can only run one task at a time; you must stop the current task before starting another, or create separate StopWatch objects for parallel timing.

By leveraging these utilities, developers can obtain clean, formatted timing reports without scattering manual timestamp calculations throughout the code, making performance analysis more maintainable and readable.

In summary, Spring's StopWatch is ideal for simple sequential task timing within Spring‑based projects, while Apache Commons' StopWatch offers richer features such as split, suspend, and time‑unit conversion, suitable for more advanced profiling scenarios.

JavaperformanceSpringApache CommonsTimingStopWatch
Java Architect Essentials
Written by

Java Architect Essentials

Committed to sharing quality articles and tutorials to help Java programmers progress from junior to mid-level to senior architect. We curate high-quality learning resources, interview questions, videos, and projects from across the internet to help you systematically improve your Java architecture skills. Follow and reply '1024' to get Java programming resources. Learn together, grow together.

0 followers
Reader feedback

How this landed with the community

login Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.