今天在敲代码的时候遇到了一个问题 在百度上找到了两种解决办法 于是说想看看到底哪个运行的比较快 开始用到了
System.currentTimeMillis();
计算代码运行开始时间戳和结束时间戳的差值来获取运行时间 敲到一半的时候 突然想到之前好像看到一种更加优雅的解决方案 ——StopWatch 这里记录一下用法
首先这个类是属于org.springframework.util
中的 所以我们只需要导入下面这个就可以了
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>5.2.9.RELEASE</version>
</dependency>
使用也很简单 start()方法开始加时 stop()停止 start()可以指定一个名字
StopWatch sw = new StopWatch("Test01");
sw.start("Demo01");
//逻辑代码
sw.stop();
sw.start("Demo02");
//逻辑代码
sw.stop();
不能嵌套使用 只等调用了stop()方法了后才能开始下一个 不然会报已经运行中的错误
Can't start StopWatch: it's already running
查看运行时间的方法有很多 常用的就是prettyPrint()
System.out.println(sw.prettyPrint());
输出也比较直观
StopWatch 'Test01': running time = 5910839 ns
---------------------------------------------
ns % Task name
---------------------------------------------
001343700 023% Demo01
004567139 077% Demo02