100个Java工具类之31:时间监视器Apache之StopWatch

100个Java工具类之31:时间监视器Apache之StopWatch

精选文章moguli202025-01-22 15:26:1949A+A-

本文主要讲述:时间监视器Apache之

org.apache.commons.lang3.time.StopWatch。

在编程过程中,常常需要计算某段程序的运行时间,常见做法是在目标程序段的前后分别记录系统毫微秒时间,通过取差得到时间差,现在有一种更好的方式是:使用apache提供的StopWatch。

相对于System.currentTimeMillis(),StopWatch更加灵活,功能更加齐全完善,推荐使用此用法。

一、使用System.currentTimeMillis()获取程序运行时间

long startTime = System.currentTimeMillis();
//运行主程序
long endTime = System.currentTimeMillis();
System.out.println("程序运行时间: " + (endTime - startTime) + "ms");
运行结果:程序运行时间: 0ms

一、使用StopWatch获取程序运行时间

//创建监视器并开启 相当于StopWatch watch = StopWatch.createStarted();
StopWatch watch = new StopWatch();
watch.start();

//记录运行时间
Thread.sleep(1000);
System.out.println("运行时间1:" + watch.getTime() + "ms");
运行结果:运行时间1:1000ms

//暂停1秒后恢复,记录运行时间
watch.suspend();
Thread.sleep(1000);//因为暂停了,因此此1秒不会计入监视器
watch.resume();
System.out.println("运行时间2:" + watch.getTime() + "ms");
运行结果:运行时间2:1001ms

//重置计时,记录运行时间
//重置后必须调start,否则会报错:Stopwatch is not running.
watch.reset();
watch.start();
Thread.sleep(1000);
System.out.println("运行时间3:" + watch.getTime() + "ms");
运行结果:运行时间3:1000ms

//设置切点
watch.split();
System.out.println("获取开始到最后一个切点的时间:" + watch.getSplitTime() + "ms");
运行结果:获取开始到最后一个切点的时间:1000ms

//停止
watch.stop();
Thread.sleep(1000);
System.out.println("开始到结束运行时间:" + watch.getTime() + "ms");
运行结果:开始到结束运行时间:1000ms

StopWatch是一个比较简单且容易上手的工具,相信你用过之后会爱不释手的~

点击这里复制本文地址 以上内容由莫古技术网整理呈现,请务必在转载分享时注明本文地址!如对内容有疑问,请联系我们,谢谢!
qrcode

莫古技术网 © All Rights Reserved.  滇ICP备2024046894号-2