StopWatch 是 属于 spring core 下的:
org.springframework.util.StopWatch
StopWatch可以监控多个任务执行,并且可以分别打印出消耗的时间,还提供了线程名自定义的操作。
例子:
public static void main(String[] args) throws Exception {
// id 可以随意修改,最好使用唯一性的ID 方便日志分析
String id = UUID.randomUUID().toString();
System.out.println("id:" + id);
// 最好使用StopWatch(string id)的方法 后续可以更好的分析监控
// StopWatch 还提供了StopWatch()的方法,虽然作用一样 但是不推荐使用
StopWatch sw = new StopWatch(id);
sw.start("我要吃饭");
Thread.sleep(200);
System.out.println("当前任务名称:" + sw.currentTaskName());
sw.stop();
sw.start("我去上班");
Thread.sleep(1000);
System.out.println("当前任务名称:" + sw.currentTaskName());
sw.stop();
System.out.println("---------0----------");
// 这个方法 包含下边的sw.shortSummary(),
// 打印出了执行任务的ID 执行需要的时间 任务名 时间占比
System.out.println(sw.prettyPrint());
System.out.println("---------1----------");
System.out.println(sw.shortSummary());
System.out.println("---------2----------");
// stop后它的值为null
System.out.println(sw.currentTaskName());
System.out.println("---------3---------");
// 最后一个任务的相关信息
System.out.println(sw.getLastTaskName());
System.out.println("---------4---------");
System.out.println(sw.getLastTaskInfo());
System.out.println("---------5---------");
// 任务总的耗时 如果你想获取到每个任务详情(包括它的任务名、耗时等等)可使用
System.out.println("所有任务总耗时:" + sw.getTotalTimeMillis());
System.out.println("任务总数:" + sw.getTaskCount());
System.out.println("所有任务详情:" + sw.getTaskInfo()); // 拿到所有的任务
}
执行结果:
id:42fe909c-61c6-471b-b9fd-2d70df813981
当前任务名称:我要吃饭
当前任务名称:我去上班
---------0----------
StopWatch '42fe909c-61c6-471b-b9fd-2d70df813981': running time = 1207478300 ns
---------------------------------------------
ns % Task name
---------------------------------------------
204081500 017% 我要吃饭
1003396800 083% 我去上班
---------1----------
StopWatch '42fe909c-61c6-471b-b9fd-2d70df813981': running time = 1207478300 ns
---------2----------
null
---------3---------
我去上班
---------4---------
org.springframework.util.StopWatch$TaskInfo@3339ad8e
---------5---------
所有任务总耗时:1207
任务总数:2
所有任务详情:[Lorg.springframework.util.StopWatch$TaskInfo;@555590