平时项目中统计耗时都用System.currentTimeMillis,最近看到一个spring-StopWatch统计耗时,其用法简单明了,比传统统计耗时方法好用。
StopWatch 的内部是通过 System.nanoTime()
来计时的,本质和 System.currentTimeMillis()
差别并不大。
nanoTime 比 currentTimeMillis 的粒度更细,前者是以纳秒为单位,后者是以毫秒为单位。
其实spring,hutool 工具库和 Apache common 工具包都提供了各自的 StopWatch。
以下为Spring-StopWatch示例(hutool 工具库和Spring-StopWatch用法相同,hutool 工具库底层来自于Spring-StopWatch)
new一个StopWatch对象即可,调用start和stop方法来统计耗时,很清晰明了。
Apache common 工具包稍微有点不同,获取StopWatch对象方式不一样。