6种快速统计代码执行时间的方法,真香!(3)

2023-05-02 来源:飞速影视
StopWatch stopWatch = new StopWatch(); // 开始时间 stopWatch.start(); // 执行时间(1s) Thread.sleep(1000); // 结束时间 stopWatch.stop(); // 统计执行时间(秒) System.out.printf("执行时长:%d 秒.%n", stopWatch.getTotalTimeSeconds()); // %n 为换行 // 统计执行时间(毫秒) System.out.printf("执行时长:%d 毫秒.%n", stopWatch.getTotalTimeMillis()); // 统计执行时间(纳秒) System.out.printf("执行时长:
%d 纳秒.%n", stopWatch.getTotalTimeNanos());
以上程序的执行结果为:
执行时长:0.9996313 秒. 执行时长:999 毫秒. 执行时长:999631300 纳秒.
小贴士:Thread#sleep 方法的执行时间稍有偏差,在 1s 左右都是正常的。
方法五:commons-lang3 StopWatch
如果我们使用的是普通项目,那我们可以用 Apache commons-lang3 中的StopWatch 对象来实现时间统计,首先先添加 commons-lang3 的依赖:
<!-- https://mvnrepository.com/artifact/org.apache.commons/commons-lang3 --> <dependency> <groupId>org.apache.commons</groupId> <artifactId>commons-lang3</artifactId> <version>3.10</version> </dependency>
然后编写时间统计代码:
import org.apache.commons.lang3.time.StopWatch; import java.util.concurrent.TimeUnit; public class TimeIntervalTest { public static void main(String[] args) throws InterruptedException { StopWatch stopWatch = new StopWatch(); // 开始时间 stopWatch.start(); // 执行时间(1s) Thread.sleep(1000); // 结束时间 stopWatch.stop(); // 统计执行时间(秒) System.out.println("执行时长:
相关影视
合作伙伴
本站仅为学习交流之用,所有视频和图片均来自互联网收集而来,版权归原创者所有,本网站只提供web页面服务,并不提供资源存储,也不参与录制、上传
若本站收录的节目无意侵犯了贵司版权,请发邮件(我们会在3个工作日内删除侵权内容,谢谢。)

www.fs94.org-飞速影视 粤ICP备74369512号