前言
开发中,为了评估性能,我们通常会使用System.currentTimeMillis() 去计算程序运行耗时
long startTime=System.currentTimeMillis();
//业务代码
...
long endTime=System.currentTimeMillis();
System.out.println("耗时:"+ (endTime-startTime)+" ms");
如何使用StopWatch优雅的做程序计时器呢?
StopWatch
示例如下
@Test
public void testStopWatch() {
StopWatch stopWatch = new StopWatch();
stopWatch.start("构建map装载10条记录");
Map<Integer, Integer> map = new HashMap<>();
for (int i = 0; i < 10; i++) {
map.put(i, i + 100);
}
stopWatch.stop();
stopWatch.start("forEach遍历map并输出");
map.forEach((k,v)->{
System.out.println(k+"="+v);
});
stopWatch.stop();
stopWatch.start("iterator遍历map并输出");
Iterator<Map.Entry<Integer, Integer>> iterator = map.entrySet().iterator();
while(iterator.hasNext()){
Map.Entry<Integer, Integer> next = iterator.next();
System.out.println(next.getKey()+"="+next.getValue());
}
stopWatch.stop();
System.out.println("最后一个任务耗时:"+stopWatch.getLastTaskTimeNanos()+" ns");
System.out.println("任务总耗时:"+stopWatch.getTotalTimeNanos()+" ns");
System.out.println(stopWatch.prettyPrint());
}
运行结果输出,可以看到StopWatch能优雅的显示程序各任务的耗时和占比。
StopWatch各方法解释
- prettyPrint:格式化输出
- getTotalTimeNanos:总消耗的时间,单位纳秒
- getLastTaskTimeNanos:最后一个任务消耗的时间,单位纳秒
- getLastTaskInfo: 最后一个任务的信息
- getTaskInfo: 所有任务的信息(数组)
- getTaskCount: 任务数
- startTask(“任务名称”): 任务的开始,传入任务名称
- stopTask: 停止计时器
- setKeepTaskList: 是否维护TaskList,如果为false,则不维护TaskList