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

我们在日常开发中经常需要测试一些代码的执行时间,但又不想使用向 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 对象统计多段代码的执行时间,也可以通过指定时间类型直接统计出对应的时间间隔,比如我们可以指定时间的统计单位,如秒、毫秒、纳秒等类型。

互动话题

你还知道哪些统计代码执行时间的方法吗?欢迎评论区补充留言。

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/546030.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

fltk 库

fltk是一个小型、开源、支持OpenGL 、跨平台&#xff08;windows,linux,mac OSX)的GUI库&#xff0c;它兼容xforms 图形库&#xff08;unix/linux下的一个C语言图形库)&#xff0c;所以可以用来开发模块化的程序&#xff0c;同时也可以使用面向对象开发程序&#xff0c;使用起来…

人工智能ai 学习_人工智能中强化学习的要点

人工智能ai 学习As discussed earlier, in Reinforcement Learning, the agent takes decisions in order to attain maximum rewards. These rewards are the reinforcements through which the agent learns in this type of agent. 如前所述&#xff0c;在“ 强化学习”中 &…

第四章 计算机软件安装与调试

*(%)^*&!*第一讲 系统BIOS和CMOS参数设置&#xff08;1&#xff09;一、BIOS、CMOS的基本概念1.BIOS的含义BIOS是只读存储器基本输入/输出系统的简写&#xff0c;是被雇花道计算机主板ROM芯片上的一组程序&#xff0c;为计算机提供最低级、最直接的硬件控制。2.CMOS的含义C…

连夜整理了几个开源项目,毕设/练手/私活一条龙!

一直以来&#xff0c;总有小伙伴问说&#xff1a;诶&#xff0c;有没有什么好的项目推荐啊&#xff0c;想参考使用。一般用途无非如下几种情况&#xff1a;自学练手&#xff1a;从书本和博客的理论学习&#xff0c;过渡到实践练手吸收项目经验&#xff0c;找工作写简历时能参考…

MPI编程简单介绍

第三章 MPI编程 3.1 MPI简单介绍 多线程是一种便捷的模型&#xff0c;当中每一个线程都能够訪问其他线程的存储空间。因此&#xff0c;这样的模型仅仅能在共享存储系统之间移植。一般来讲&#xff0c;并行机不一定在各处理器之间共享存储&#xff0c;当面向非共享存储系统开发…

英语电视节目网站

最近想练习一下英语听力&#xff0c;看到了一个网站&#xff0c;感觉好像还不错&#xff0c;播放比较流畅&#xff0c;语速相对来说比较慢&#xff0c;发音比较清晰。 链接&#xff1a;CSPAN 还有更多网站见&#xff1a;Broadband-Television BON CNC 英文在线广播&#x…

三位bcd加法计数器_两个8位BCD编号的加法| 8085微处理器

三位bcd加法计数器Problem statement: 问题陈述&#xff1a; To perform addition operation between two 8-bit BCD numbers using 8085 microprocessor. 使用8085微处理器在两个8位BCD编号之间执行加法运算。 Algorithm: 算法&#xff1a; Load the two numbers in HL pai…

第五章 计算机故障诊断与排除

*(%)^*&!*第一讲 计算机故障基础及电源类故障诊断和维护一、计算机故障的分类1.硬件故障硬件故障是指用户使用不当或由于电子元件故障而引起计算机硬件不能正常运行的故障。常见的硬件故障现象包括&#xff1a;&#xff08;1&#xff09;电源故障&#xff0c;导致没有供电或…

图灵奖演讲稿

刚刚读温伯格 的《理解专业程序员》&#xff0c;书中提到Floyd 图灵奖演讲中关于编程范式(programming paradigm )&#xff08;also see here )的演讲稿值得每个与编程有关的人一读&#xff0c;所以搜索了一些图灵奖相关的一些网络资源。 图灵奖主页 部分图灵奖演讲稿 其他资…

最简单的6种防止数据重复提交的方法!(干货)

有位朋友&#xff0c;某天突然问磊哥&#xff1a;在 Java 中&#xff0c;防止重复提交最简单的方案是什么&#xff1f;这句话中包含了两个关键信息&#xff0c;第一&#xff1a;防止重复提交&#xff1b;第二&#xff1a;最简单。于是磊哥问他&#xff0c;是单机环境还是分布式…

JavaScript匿名函数与托付

<1> <html xmlns"http://www.w3.org/1999/xhtml"> <head><!-- C#匿名函数--><title></title><script type"text/javascript">var f1 function (x, y) { //【1】 定义一个匿名函数&#xff0c;用变量f1来指向它…

第六章 计算机性能测试

*(%)^*&!*第一讲 系统优化一、Windows XP系统的优化功能1.启动速度加速选择“开始→运行”选项&#xff0c;再出现的对话框中输入“msconfig”&#xff0c;然后单击“确定”按钮&#xff0c;弹出“系统配置实用程序”对话框。在启动选项卡中将不需要加载启动的程序前面的对…

c#读取整数空格_C ++程序声明,读取和打印动态整数数组

c#读取整数空格Prerequisite: new and delete operator in C 先决条件&#xff1a; C 中的new和delete运算符 Here, we will learn how to declare, read and print dynamically allocated array? 在这里&#xff0c;我们将学习如何声明&#xff0c;读取和打印动态分配的数组…

math for programmers(转载)

英文内容&#xff0c;来自http://steve-yegge.blogspot.com/2006/03/math-for-programmers.html 翻译版见这里 相关内容见c2.com 原文内容如下&#xff1a; Ive been working for the past 15 months on repairing my rusty math skills, ever since I read a biography o…

漫画:如何证明sleep不释放锁,而wait释放锁?

wait 加锁示例public class WaitDemo {private static Object locker new Object();public static void main(String[] args) throws InterruptedException {WaitDemo waitDemo new WaitDemo();// 启动新线程&#xff0c;防止主线程被休眠new Thread(() -> {try {waitDemo…

设计模式 之 建造者

建造者模式&#xff08;Builder Pattern&#xff09; 一听这个名字&#xff0c;你可能就会猜到一二分了。建造者简单理解就是造东西&#xff0c;仅仅只是建造者模式建造的不是一个简单的东西&#xff0c;是一个比較复杂的东西。就好像盖房子&#xff0c;须要打地基、砌墙、灌…

stl string 函数_使用C ++ STL中的string :: append()函数将文本追加到字符串

stl string 函数append() is a library function of <string> header, it is used to append the extra characters/text in the string. append()是<string>标头的库函数&#xff0c;用于在字符串中附加多余的字符/文本。 Syntax: 句法&#xff1a; string&…

ABCDE类IP地址的解释

A类地址第1字节为网络地址&#xff0c;其它3个字节为主机地址。另外第1个字节的最高位固定为0。 A类地址范围&#xff1a;1.0.0.0到127.255.255.255。 A类地址中的私有地址和保留地址&#xff1a; 10.0.0.0到10.255.255.255是私有地址&#xff08;所谓的私有地址就是在互联网上…

身体健康小窍门

身体健康对于每个人来说都是第一重要的&#xff0c;找到的一些健康小窍门&#xff0c;可能有帮助&#xff1a; 1&#xff09;单鼻呼吸&#xff08; 来源 &#xff09;&#xff1a;中午以前最好常练习用左鼻子呼吸&#xff0c;没事的时候你就用手很自然的托住右边面颊&#xf…

支付宝上市,让我损失了2000万(盘点这些年错过的机会)

选择大于努力&#xff01;这句话在之前&#xff0c;我只是用排除法来解释它&#xff08;如果你的选择是错的&#xff0c;那么走的越快就离目标越远&#xff09;&#xff0c;而如今几次亲身的经历&#xff0c;却给了我不同的答案...近几天支付宝上市的事儿&#xff0c;传的沸沸扬…