Java:stopWatch用法

郎家岭伯爵 2026年04月14日 4次浏览

前言

最近在做项目时发现有使用 stopWatch 工具来实现性能分析,这里记录一下。

实现

Hutool工具类实现

这里使用 Hutool 工具类里的 stopWatch 来实现。

示例代码段:

package org.example.test;

import cn.hutool.core.date.StopWatch;

import java.util.concurrent.TimeUnit;

/**
 * @Author LANGJIALINGBOJUE
 * @Date 2026年4月14日20:06:57
 * @Description TODO
 */
public class Test7 {

    public static void main(String[] args) throws InterruptedException {
        StopWatch test = StopWatch.create("test");

        test.start("test1");
        Thread.sleep(1000);
        test.stop();

        test.start("test2");
        Thread.sleep(2000);
        test.stop();

        System.out.println(test.shortSummary());
        System.out.println(test.shortSummary(TimeUnit.MILLISECONDS));
        System.out.println(test.shortSummary(TimeUnit.SECONDS));
        System.out.println("\n");
        System.out.println(test.prettyPrint());
    }
}

输出:

StopWatch 'test': running time = 3014729600 ns
StopWatch 'test': running time = 3014 ms
StopWatch 'test': running time = 3 s


StopWatch 'test': running time = 3014729600 ns
---------------------------------------------
ns         %     Task name
---------------------------------------------
1003440700  33%   test1
2011288900  67%   test2


Process finished with exit code 0

SpringFramework实现

SpringFramework 也提供了类似的用法,但感觉没有 Hutool 好用。

示例代码段:

package org.example.test;

import org.springframework.util.StopWatch;

/**
 * @Author LIYUWEI
 * @Date 2026年04月14日20:08:54
 * @Description TODO
 */
public class Test7 {
    public static void main(String[] args) throws InterruptedException {
        StopWatch stopWatch = new StopWatch("springframework-test");

        stopWatch.start("test1");
        Thread.sleep(1000);
        stopWatch.stop();

        stopWatch.start("test2");
        Thread.sleep(2000);
        stopWatch.stop();

        System.out.println(stopWatch.prettyPrint());
        System.out.println(stopWatch.shortSummary());
        System.out.println(stopWatch.getTotalTimeMillis());
        System.out.println(stopWatch.getTotalTimeSeconds());
    }
}

输出:

StopWatch 'springframework-test': running time = 2016272200 ns
---------------------------------------------
ns         %     Task name
---------------------------------------------
1002648600  050%  test1
1013623600  050%  test2

StopWatch 'springframework-test': running time = 2016272200 ns
2016
2.0162722

Process finished with exit code 0

总结

记录下 stopWatch 的用法,还挺好用的。