统计代码耗时的工具
项目中通常会通过打印时间来查看某段任务的耗时,进行项目优化通常会通过 t2-t1 的方式进行统计
public static void main(String[] args) throws InterruptedException { StopWatchTest.test0();// StopWatchTest.test1();}
public static void test0() throws InterruptedException { long start = System.currentTimeMillis(); // do something Thread.sleep(100); long end = System.currentTimeMillis(); long start2 = System.currentTimeMillis(); // do something Thread.sleep(200); long end2 = System.currentTimeMillis(); System.out.println("任务1执行耗时:" + (end - start)); System.out.println("任务2执行耗时:" + (end2 - start2));}
复制代码
spring StopWatch 用法
spring-framework 提供了一个 StopWatch 类可以做类似任务执行时间控制,也就是封装了一个对开始时间,结束时间记录操作的 Java 类,小例一则如下
栗子:
package com.example.stopwatch;
import org.springframework.util.StopWatch;
public class TestStopWatch { private void test() throws InterruptedException { StopWatch sw = new StopWatch();
sw.start("任务1"); Thread.sleep(1000); sw.stop();
sw.start("任务2"); Thread.sleep(2000); sw.stop();
sw.start("任务3"); 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()); }
public static void main(String []argv) throws InterruptedException { TestStopWatch testStopWatch = new TestStopWatch(); testStopWatch.test(); }}
复制代码
结果
StopWatch '': running time (millis) = 3518-----------------------------------------ms % Task name-----------------------------------------00998 028% 任务102020 057% 任务200500 014% 任务3 3518任务3org.springframework.util.StopWatch$TaskInfo@5b2133b13
复制代码
一个 StopWatch 实例一次只能开启一个 task,不能同时 start 多个 task,并且在该 task 未 stop 之前不能 start 一个新的 task,必须在该 task stop 之后才能开启新的 task,若要一次开启多个,需要 new 不同的 StopWatch 实例.
计时器工具-TimeInterval
Hutool 通过封装 TimeInterval 实现计时器功能,即可以计算方法或过程执行的时间。
TimeInterval 支持分组计时,方便对比时间。
使用
TimeInterval timer = DateUtil.timer();
//---------------------------------//-------这是执行过程//---------------------------------
timer.interval();//花费毫秒数timer.intervalRestart();//返回花费时间,并重置开始时间timer.intervalMinute();//花费分钟数
复制代码
也可以实现分组计时:
final TimeInterval timer = new TimeInterval();
// 分组1timer.start("1");ThreadUtil.sleep(800);
// 分组2timer.start("2");ThreadUtil.sleep(900);
Console.log("Timer 1 took {} ms", timer.intervalMs("1"));Console.log("Timer 2 took {} ms", timer.intervalMs("2"));
复制代码
评论