依赖
注意:StopWatch并不是JDK自带的类,需要引入spring
类库,这一点很多文章都没说
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>5.3.31</version>
</dependency>
导入类
import org.springframework.util.StopWatch;
使用示例
示例1:统计单任务耗时
package com.demo;
import org.springframework.util.StopWatch;
public class StopWatchDemo {
public static void main(String[] args) throws InterruptedException {
StopWatch stopWatch = new StopWatch();
stopWatch.start();
Thread.sleep(3);
stopWatch.stop();
double totalTimeSeconds = stopWatch.getTotalTimeSeconds();
// 打印总耗时
System.out.println(totalTimeSeconds);
}
}
示例2:统计多任务耗时
package com.demo;
import org.springframework.util.StopWatch;
public class StopWatchDemo {
public static void main(String[] args) throws InterruptedException {
StopWatch stopWatch = new StopWatch();
// 任务1
stopWatch.start("任务1");
Thread.sleep(300);
stopWatch.stop();
// 任务2
stopWatch.start("任务2");
Thread.sleep(300);
stopWatch.stop();
// 打印耗时
System.out.println(stopWatch.prettyPrint());
}
}
输出
StopWatch '': running time = 600378510 ns
---------------------------------------------
ns % Task name
---------------------------------------------
300221065 050% 任务1
300157445 050% 任务2