当前位置:   article > 正文

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

java 统计方法执行时间

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

方法一:System.currentTimeMillis

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

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

以上程序的执行结果为:

执行时长:1000 毫秒.

方法二:System.nanoTime

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

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

以上程序的执行结果为:

执行时长:1000769200 纳秒.

小贴士:1 毫秒 = 100 万纳秒。

方法三:new Date

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

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

以上程序的执行结果为:

执行时长:1000 毫秒.

方法四:Spring StopWatch

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

  1. StopWatch stopWatch = new StopWatch();
  2. // 开始时间
  3. stopWatch.start();
  4. // 执行时间(1s)
  5. Thread.sleep(1000);
  6. // 结束时间
  7. stopWatch.stop();
  8. // 统计执行时间(秒)
  9. System.out.printf("执行时长:%d 秒.%n", stopWatch.getTotalTimeSeconds()); // %n 为换行
  10. // 统计执行时间(毫秒)
  11. System.out.printf("执行时长:%d 毫秒.%n", stopWatch.getTotalTimeMillis()); 
  12. // 统计执行时间(纳秒)
  13. System.out.printf("执行时长:%d 纳秒.%n", stopWatch.getTotalTimeNanos());

以上程序的执行结果为:

执行时长:0.9996313 秒. 执行时长:999 毫秒. 执行时长:999631300 纳秒.

小贴士:Thread#sleep 方法的执行时间稍有偏差,在 1s 左右都是正常的。

方法五:commons-lang3 StopWatch

如果我们使用的是普通项目,那我们可以用 Apache commons-lang3 中的 StopWatch 对象来实现时间统计,首先先添加 commons-lang3 的依赖:

  1. <!-- https://mvnrepository.com/artifact/org.apache.commons/commons-lang3 -->
  2. <dependency>
  3.   <groupId>org.apache.commons</groupId>
  4.   <artifactId>commons-lang3</artifactId>
  5.   <version>3.10</version>
  6. </dependency>

然后编写时间统计代码:

  1. import org.apache.commons.lang3.time.StopWatch;
  2. import java.util.concurrent.TimeUnit;
  3. public class TimeIntervalTest {
  4.     public static void main(String[] args) throws InterruptedException {
  5.         StopWatch stopWatch = new StopWatch();
  6.         // 开始时间
  7.         stopWatch.start();
  8.         // 执行时间(1s)
  9.         Thread.sleep(1000);
  10.         // 结束时间
  11.         stopWatch.stop();
  12.         // 统计执行时间(秒)
  13.         System.out.println("执行时长:" + stopWatch.getTime(TimeUnit.SECONDS) + " 秒.");
  14.         // 统计执行时间(毫秒)
  15.         System.out.println("执行时长:" + stopWatch.getTime(TimeUnit.MILLISECONDS) + " 毫秒.");
  16.         // 统计执行时间(纳秒)
  17.         System.out.println("执行时长:" + stopWatch.getTime(TimeUnit.NANOSECONDS) + " 纳秒.");
  18.     }
  19. }

以上程序的执行结果为:

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

执行时长:1000555100 纳秒.

方法六:Guava Stopwatch

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

  1. <!-- https://mvnrepository.com/artifact/com.google.guava/guava -->
  2. <dependency>
  3.   <groupId>com.google.guava</groupId>
  4.   <artifactId>guava</artifactId>
  5.   <version>29.0-jre</version>
  6. </dependency>

然后编写时间统计代码:

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

以上程序的执行结果为:

执行时长:1 秒.

执行时长:1000 豪秒.

原理分析

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

1.Spring StopWatch 原理分析

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

  1. package org.springframework.util;
  2. import java.text.NumberFormat;
  3. import java.util.LinkedList;
  4. import java.util.List;
  5. import java.util.concurrent.TimeUnit;
  6. import org.springframework.lang.Nullable;
  7. public class StopWatch {
  8.     private final String id;
  9.     private boolean keepTaskList;
  10.     private final List<StopWatch.TaskInfo> taskList;
  11.     private long startTimeNanos;
  12.     @Nullable
  13.     private String currentTaskName;
  14.     @Nullable
  15.     private StopWatch.TaskInfo lastTaskInfo;
  16.     private int taskCount;
  17.     private long totalTimeNanos;
  18.     public StopWatch() {
  19.         this("");
  20.     }
  21.     public StopWatch(String id) {
  22.         this.keepTaskList = true;
  23.         this.taskList = new LinkedList();
  24.         this.id = id;
  25.     }
  26.     public String getId() {
  27.         return this.id;
  28.     }
  29.     public void setKeepTaskList(boolean keepTaskList) {
  30.         this.keepTaskList = keepTaskList;
  31.     }
  32.     public void start() throws IllegalStateException {
  33.         this.start("");
  34.     }
  35.     public void start(String taskName) throws IllegalStateException {
  36.         if (this.currentTaskName != null) {
  37.             throw new IllegalStateException("Can't start StopWatch: it's already running");
  38.         } else {
  39.             this.currentTaskName = taskName;
  40.             this.startTimeNanos = System.nanoTime();
  41.         }
  42.     }
  43.     public void stop() throws IllegalStateException {
  44.         if (this.currentTaskName == null) {
  45.             throw new IllegalStateException("Can't stop StopWatch: it's not running");
  46.         } else {
  47.             long lastTime = System.nanoTime() - this.startTimeNanos;
  48.             this.totalTimeNanos += lastTime;
  49.             this.lastTaskInfo = new StopWatch.TaskInfo(this.currentTaskName, lastTime);
  50.             if (this.keepTaskList) {
  51.                 this.taskList.add(this.lastTaskInfo);
  52.             }
  53.             ++this.taskCount;
  54.             this.currentTaskName = null;
  55.         }
  56.     }
  57.     // .... 忽略其他代码
  58. }

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

2.Google Stopwatch 原理分析

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

  1. public final class Stopwatch {
  2.     private final Ticker ticker;
  3.     private boolean isRunning;
  4.     private long elapsedNanos;
  5.     private long startTick;
  6.     @CanIgnoreReturnValue
  7.     public Stopwatch start() {
  8.         Preconditions.checkState(!this.isRunning, "This stopwatch is already running.");
  9.         this.isRunning = true;
  10.         this.startTick = this.ticker.read();
  11.         return this;
  12.     }
  13.     @CanIgnoreReturnValue
  14.     public Stopwatch stop() {
  15.         long tick = this.ticker.read();
  16.         Preconditions.checkState(this.isRunning, "This stopwatch is already stopped.");
  17.         this.isRunning = false;
  18.         this.elapsedNanos += tick - this.startTick;
  19.         return this;
  20.     }
  21.     // 忽略其他源码...
  22. }

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

  1. public abstract class Ticker {
  2.     private static final Ticker SYSTEM_TICKER = new Ticker() {
  3.         public long read() {
  4.             return Platform.systemNanoTime();
  5.         }
  6.     };
  7.     protected Ticker() {
  8.     }
  9.     public abstract long read();
  10.     public static Ticker systemTicker() {
  11.         return SYSTEM_TICKER;
  12.     }
  13. }
  14. final class Platform {
  15.     private static final Logger logger = Logger.getLogger(Platform.class.getName());
  16.     private static final PatternCompiler patternCompiler = loadPatternCompiler();
  17.     private Platform() {
  18.     }
  19.     static long systemNanoTime() {
  20.         return System.nanoTime();
  21.     }
  22.     // 忽略其他源码...
  23. }

从上述源码可以看出 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 使用示例如下:

  1. import com.google.common.base.Stopwatch;
  2. import java.util.concurrent.TimeUnit;
  3. public class TimeIntervalTest {
  4.     public static void main(String[] args) throws InterruptedException {
  5.         // 创建并启动计时器
  6.         Stopwatch stopwatch = Stopwatch.createStarted();
  7.         // 执行时间(1s)
  8.         Thread.sleep(1000);
  9.         // 停止计时器
  10.         stopwatch.stop();
  11.         // 执行统计
  12.         System.out.printf("执行时长:%d 毫秒. %n",
  13.                 stopwatch.elapsed(TimeUnit.MILLISECONDS));
  14.         // 清空计时器
  15.         stopwatch.reset();
  16.         // 再次启动统计
  17.         stopwatch.start();
  18.         // 执行时间(2s)
  19.         Thread.sleep(2000);
  20.         // 停止计时器
  21.         stopwatch.stop();
  22.         // 执行统计
  23.         System.out.printf("执行时长:%d 秒. %n",
  24.                 stopwatch.elapsed(TimeUnit.MILLISECONDS));
  25.     }
  26. }

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

互动话题

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

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/天景科技苑/article/detail/823416
推荐阅读
相关标签
  

闽ICP备14008679号