我们在日常开发中经常需要测试一些代码的执行时间,但又不想使用向 JMH(Java Microbenchmark Harness,Java 微基准测试套件)这么重的测试框架,所以本文就汇总了一些 Java 中比较常用的执行时间统计方法,总共包含以下 6 种,如下图所示:

方法一:System.currentTimeMillis

此方法为 Java 内置的方法,使用 System#currentTimeMillis 来统计执行的时间(统计单位:毫秒),示例代码如下:

public class TimeIntervalTest {public static void main(String[] args) throws InterruptedException {// 开始时间long stime = System.currentTimeMillis();// 执行时间(1s)Thread.sleep(1000);// 结束时间long etime = System.currentTimeMillis();// 计算执行时间System.out.printf("执行时长:%d 毫秒.", (etime - stime));}
}

以上程序的执行结果为:

执行时长:1000 毫秒.

方法二:System.nanoTime

此方法为 Java 内置的方法,使用 System#nanoTime 来统计执行时间(统计单位:纳秒),它的执行方法和 System#currentTimeMillis 类似,示例代码如下:

public class TimeIntervalTest {public static void main(String[] args) throws InterruptedException {// 开始时间long stime = System.nanoTime();// 执行时间(1s)Thread.sleep(1000);// 结束时间long etime = System.nanoTime();// 计算执行时间System.out.printf("执行时长:%d 纳秒.", (etime - stime));}
}

以上程序的执行结果为:

执行时长:1000769200 纳秒.
小贴士:1 毫秒 = 100 万纳秒。

方法三:new Date

此方法也是 Java 的内置方法,在开始执行前 new Date() 创建一个当前时间对象,在执行结束之后 new Date() 一个当前执行时间,然后再统计两个 Date 的时间间隔,示例代码如下:

import java.util.Date;public class TimeIntervalTest {public static void main(String[] args) throws InterruptedException {// 开始时间Date sdate = new Date();// 执行时间(1s)Thread.sleep(1000);// 结束时间Date edate = new Date();//  统计执行时间(毫秒)System.out.printf("执行时长:%d 毫秒." , (edate.getTime() - sdate.getTime())); }
}

以上程序的执行结果为:

执行时长:1000 毫秒.

方法四:Spring StopWatch

如果我们使用的是 Spring 或 Spring Boot 项目,可以在项目中直接使用 StopWatch 对象来统计代码执行时间,示例代码如下:

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("执行时长:" + stopWatch.getTime(TimeUnit.SECONDS) + " 秒.");// 统计执行时间(毫秒)System.out.println("执行时长:" + stopWatch.getTime(TimeUnit.MILLISECONDS) + " 毫秒.");// 统计执行时间(纳秒)System.out.println("执行时长:" + stopWatch.getTime(TimeUnit.NANOSECONDS) + " 纳秒.");}
}

以上程序的执行结果为:

执行时长:1 秒. 执行时长:1000 毫秒.
执行时长:1000555100 纳秒.

方法六:Guava Stopwatch

除了 Apache 的 commons-lang3 外,还有一个常用的 Java 工具包,那就是 Google 的 Guava,Guava 中也包含了 Stopwatch 统计类。首先先添加 Guava 的依赖:

<!-- https://mvnrepository.com/artifact/com.google.guava/guava -->
<dependency><groupId>com.google.guava</groupId><artifactId>guava</artifactId><version>29.0-jre</version>
</dependency>

然后编写时间统计代码:

import com.google.common.base.Stopwatch;import java.util.concurrent.TimeUnit;public class TimeIntervalTest {public static void main(String[] args) throws InterruptedException {// 创建并启动计时器Stopwatch stopwatch = Stopwatch.createStarted();// 执行时间(1s)Thread.sleep(1000);// 停止计时器stopwatch.stop();// 执行时间(单位:秒)System.out.printf("执行时长:%d 秒. %n", stopwatch.elapsed().getSeconds()); // %n 为换行// 执行时间(单位:毫秒)System.out.printf("执行时长:%d 豪秒.", stopwatch.elapsed(TimeUnit.MILLISECONDS));}
}

以上程序的执行结果为:

执行时长:1 秒.
执行时长:1000 豪秒.

原理分析

本文我们从 Spring 和 Google 的 Guava 源码来分析一下,它们的 StopWatch 对象底层是如何实现的?

1.Spring StopWatch 原理分析

在 Spring 中 StopWatch 的核心源码如下:

package org.springframework.util;import java.text.NumberFormat;
import java.util.LinkedList;
import java.util.List;
import java.util.concurrent.TimeUnit;
import org.springframework.lang.Nullable;public class StopWatch {private final String id;private boolean keepTaskList;private final List<StopWatch.TaskInfo> taskList;private long startTimeNanos;@Nullableprivate String currentTaskName;@Nullableprivate StopWatch.TaskInfo lastTaskInfo;private int taskCount;private long totalTimeNanos;public StopWatch() {this("");}public StopWatch(String id) {this.keepTaskList = true;this.taskList = new LinkedList();this.id = id;}public String getId() {return this.id;}public void setKeepTaskList(boolean keepTaskList) {this.keepTaskList = keepTaskList;}public void start() throws IllegalStateException {this.start("");}public void start(String taskName) throws IllegalStateException {if (this.currentTaskName != null) {throw new IllegalStateException("Can't start StopWatch: it's already running");} else {this.currentTaskName = taskName;this.startTimeNanos = System.nanoTime();}}public void stop() throws IllegalStateException {if (this.currentTaskName == null) {throw new IllegalStateException("Can't stop StopWatch: it's not running");} else {long lastTime = System.nanoTime() - this.startTimeNanos;this.totalTimeNanos += lastTime;this.lastTaskInfo = new StopWatch.TaskInfo(this.currentTaskName, lastTime);if (this.keepTaskList) {this.taskList.add(this.lastTaskInfo);}++this.taskCount;this.currentTaskName = null;}}// .... 忽略其他代码
}

从上述 start()stop() 的源码中可以看出,Spring 实现时间统计的本质还是使用了 Java 的内置方法 System.nanoTime() 来实现的。

2.Google Stopwatch 原理分析

Google Stopwatch 实现的核心源码如下:

public final class Stopwatch {private final Ticker ticker;private boolean isRunning;private long elapsedNanos;private long startTick;@CanIgnoreReturnValuepublic Stopwatch start() {Preconditions.checkState(!this.isRunning, "This stopwatch is already running.");this.isRunning = true;this.startTick = this.ticker.read();return this;}@CanIgnoreReturnValuepublic Stopwatch stop() {long tick = this.ticker.read();Preconditions.checkState(this.isRunning, "This stopwatch is already stopped.");this.isRunning = false;this.elapsedNanos += tick - this.startTick;return this;}// 忽略其他源码...
}

从上述源码中可以看出 Stopwatch 对象中调用了 ticker 类来实现时间统计的,那接下来我们进入 ticker 类的实现源码:

public abstract class Ticker {private static final Ticker SYSTEM_TICKER = new Ticker() {public long read() {return Platform.systemNanoTime();}};protected Ticker() {}public abstract long read();public static Ticker systemTicker() {return SYSTEM_TICKER;}
}
final class Platform {private static final Logger logger = Logger.getLogger(Platform.class.getName());private static final PatternCompiler patternCompiler = loadPatternCompiler();private Platform() {}static long systemNanoTime() {return System.nanoTime();}// 忽略其他源码...
}

从上述源码可以看出 Google Stopwatch 实现时间统计的本质还是调用了 Java 内置的 System.nanoTime() 来实现的。

结论

对于所有框架的 StopWatch 来说,其底层都是通过调用 Java 内置的 System.nanoTime() 得到两个时间,开始时间和结束时间,然后再通过结束时间减去开始时间来统计执行时间的。

总结

本文介绍了 6 种实现代码统计的方法,其中 3 种是 Java 内置的方法:

  • System.currentTimeMillis()
  • System.nanoTime()
  • new Date()

还介绍了 3 种常用框架 spring、commons-langs3、guava 的时间统计器 StopWatch

在没有用到 spring、commons-langs3、guava 任意一种框架的情况下,推荐使用 System.currentTimeMillis()System.nanoTime() 来实现代码统计,否则建议直接使用StopWatch 对象来统计执行时间。

知识扩展—Stopwatch 让统计更方便

StopWatch 存在的意义是让代码统计更简单,比如 Guava 中 StopWatch 使用示例如下:

import com.google.common.base.Stopwatch;import java.util.concurrent.TimeUnit;public class TimeIntervalTest {public static void main(String[] args) throws InterruptedException {// 创建并启动计时器Stopwatch stopwatch = Stopwatch.createStarted();// 执行时间(1s)Thread.sleep(1000);// 停止计时器stopwatch.stop();// 执行统计System.out.printf("执行时长:%d 毫秒. %n",stopwatch.elapsed(TimeUnit.MILLISECONDS));// 清空计时器stopwatch.reset();// 再次启动统计stopwatch.start();// 执行时间(2s)Thread.sleep(2000);// 停止计时器stopwatch.stop();// 执行统计System.out.printf("执行时长:%d 秒. %n",stopwatch.elapsed(TimeUnit.MILLISECONDS));}
}

我们可以使用一个 Stopwatch 对象统计多段代码的执行时间,也可以通过指定时间类型直接统计出对应的时间间隔,比如我们可以指定时间的统计单位,如秒、毫秒、纳秒等类型。


原作者:磊哥
原文链接:6种快速统计代码执行时间的方法,真香!(史上最全)
原出处:公众号
侵删

java sleep方法_6种快速统计代码执行时间的方法,真香!(史上最全)相关推荐

  1. 6种快速统计代码执行时间的方法,真香!(史上最全)

    我们在日常开发中经常需要测试一些代码的执行时间,但又不想使用向 JMH(Java Microbenchmark Harness,Java 微基准测试套件)这么重的测试框架,所以本文就汇总了一些 Jav ...

  2. linux几种快速清空文件内容的方法

    linux几种快速清空文件内容的方法 几种快速清空文件内容的方法: $ : > filename #其中的 : 是一个占位符, 不产生任何输出. $ > filename $ echo & ...

  3. 2022年Java学习路线图,精心整理「史上最全」

    前言: 很多老铁经常问我:哪些是适合Java零基础学习的视频?应该先学哪个后学哪个?等等问题. 那么,怎么解决这些疑问? 一个系统的Java学习路线正是你最需要的,这也是为什么很多前期自学的小白们到处 ...

  4. 最小二乘模糊度去相关调整:一种快速GPS整数模糊度估计方法

    最小二乘模糊度去相关调整:一种快速GPS整数模糊度估计方法 摘要: GPS双差载波相位测量由于周期数未知而存在模糊性.当整数双差模糊度的可靠估计能够以有效的方式确定时,基于短观测时间跨度数据的高精度相 ...

  5. 计算机上根号5怎么打,根号怎么打(5种快速输入√与×号的方法)

    根号怎么打(5种快速输入√与号的方法) 1.alt+数字 我们双击单元格,进入数据输入的状态,这个时候只需要按下alt+指定的数字就能快速的输入对勾对叉号,这个利用的ASCII编码,Windows系统 ...

  6. 推荐一种快速提高英语口语的方法

    推荐一种快速提高英语口语的方法 zijan 2011-03-19 现在越来越多的外国企业在中国开设分公司,很多人有很强的技术和能力,但是英语不行进不了外企.这是因为中国糟糕的英语教育导致的,我们大家都 ...

  7. 指标异动排查中,3种快速定位异常维度的方法

    如果你对数据分析感兴趣,希望学习更多的方法论,希望听听经验分享, 欢迎移步公众号「小火龙说数据」,更多精彩原创文章与你分享! 「经验」指标异动排查中,3种快速定位异常维度的方法https://mp.w ...

  8. 史上最全讲解:JAVA中的方法 数组 类

    史上最全讲解:JAVA中的数组 方法 面向对象 文章目录 史上最全讲解:JAVA中的数组 方法 面向对象 数组 数组的定义: 数组的特点: 数组的初始化: 数组的遍历: 从前到后拿到每一个数据 方法 ...

  9. 手机投屏到电视的5种方法_安卓手机、苹果手机投屏到电视史上最全的方法

    安卓手机和苹果iPhone手机怎么投屏到电视?楼主汇总了5种投屏方法,这应该是史上最全的了.一共有5种投屏方法,大家可以选择适合自己的.方法一:iPhone手机自带的投屏功能 AirPlay 优点:快 ...

最新文章

  1. 「建模调参」之零基础入门数据挖掘
  2. Collection View Programming Guide for iOS---(四)---Using the Flow Layout
  3. 恒位油杯故障原因_厂家详解干式真空泵故障分析与保养办法
  4. ImportError: cannot import name 'six'解决
  5. Matlab中 pdist 函数详解
  6. 分享一个VisualStudio2010插件——Productivity Power Tools
  7. Maven for Eclipse 第二章 ——安装 m2eclipse插件
  8. 手把手教你使用spring cloud+dotnet core搭建微服务架构:服务治理(-)
  9. 【latex】最后一页 参考文献不平衡 左右不对齐
  10. 【AngularJs学习笔记五】AngularJS从构建项目开始
  11. javaWeb校园宿舍管理解析(二)
  12. HDU2008 数值统计【序列处理】
  13. Javascript:ES6语法简述
  14. 适用于Chrome类浏览器的喜马拉雅音频下载插件
  15. 已知圆心及半径,通过MATLAB画圆
  16. 网线水晶头 RJ45 接法
  17. 计算机视觉、图像处理学习资料汇总
  18. 计算机等级考网络课程答案,《计算机应用基础》课程考试试卷
  19. 什么是RS485总线?怎么使用RS485总线?一文了解清楚
  20. Ubuntu系统无法使用vim命令

热门文章

  1. XJOI 3866 写什么名字好呢
  2. mysql数据库在linux下的导出和导入及每天的备份
  3. spring(二)-反射、动态代理
  4. Windows C盘格式化或者同平台迁移oracle数据库
  5. matlab字符串中的换行符,如何在MATLAB中的子图中显示文本/字符串行?
  6. VS Code 下载安装并设置中文面板显示
  7. Ubuntu18.04关闭zeitgeist-datahub自启动
  8. C语言之避免编译警告:unused用法(七)
  9. Android开发之AudioManager(音频管理器)详解
  10. 一键杀死最近打开APP