目录
一 、StopWatch 简介
StopWatch:秒表,跑表的意思,我们按字面意思大概就可以推测出它是用来计算时间,监控时间之类的。允许多个任务的计时,暴露每个命名任务的总运行时间和运行时间。隐藏使用System.currentTimeMillis(),提高应用程序代码的可读性并减少计算错误的可能性
二、StopWatch使用
- 一般在开发工程中,我们统计代码运行耗时都是通过自己敲代码来完成的,例如下面代码
public static void main(String[] args) throws InterruptedException {
long start = System.currentTimeMillis();
Thread.sleep(2000);
System.out.println(System.currentTimeMillis()-start);
}
- 用StopWatch后,我们可以这样写,如代码:
public static void main(String[] args) throws InterruptedException {
StopWatch stopWatch = new StopWatch();
stopWatch.start();
Thread.sleep(2000);
stopWatch.stop();
System.out.println(stopWatch.getTotalTimeMillis());
}
-
以优雅的格式打出所有任务的耗时以及占比
public static void main(String[] args) throws InterruptedException {
StopWatch stopWatch = new StopWatch();
stopWatch.start();
Thread.sleep(2000);
stopWatch.stop();
System.out.println(stopWatch.prettyPrint());
}
-
getTotalTimeSeconds() 获取总耗时秒,同时也有获取毫秒的方法
-
prettyPrint() 优雅的格式打印结果,表格形式
-
shortSummary() 返回简短的总耗时描述
-
getTaskCount() 返回统计时间任务的数量
-
getLastTaskInfo().getTaskName() 返回最后一个任务TaskInfo对象的名称
三、单个线程使用StopWatch要多次计算执行时间
如果在单个线程我们要多次计算执行时间,那么StopWatch工具就更方便了,如下例子:
public static void main(String[] args) {
StopWatch stopWatch = new StopWatch();
for (int i = 0; i < 5; i++) {
stopWatch.start("stopWatch"+i);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
stopWatch.stop();
}
System.out.println("stopWatch task count :"+stopWatch.getTaskCount());
System.out.println("总耗时:"+stopWatch.getTotalTimeSeconds()+"秒");
for (StopWatch.TaskInfo taskInfo : stopWatch.getTaskInfo()) {
System.out.println(taskInfo.getTaskName()+"耗时:"+taskInfo.getTimeSeconds()+"秒");
}
}
打印结果如下:
stopWatch task count :5
总耗时:5.0263041秒
stopWatch0耗时:0.9979452秒
stopWatch1耗时:1.0050517秒
stopWatch2耗时:1.0095104秒
stopWatch3耗时:1.0084876秒
stopWatch4耗时:1.0053092秒
扩展:当前 apache 工具包commons-lang3 也有 StopWatch 里面提供了更多的方法可供使用。比如,suspend 方法暂停计时、resume 方法恢复计时、reset 重新计时。
总结:StopWatch 的内部是通过 System.nanoTime()
来计时的,其实和 System.currentTimeMillis()
差别并不大。只不过nanoTime 比 currentTimeMillis 的粒度更细,前者是以纳秒为单位,后者是以毫秒为单位。