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

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

方法五: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;
    @Nullable
    private String currentTaskName;
    @Nullable
    private 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;
    @CanIgnoreReturnValue
    public Stopwatch start() {
        Preconditions.checkState(!this.isRunning, "This stopwatch is already running.");
        this.isRunning = true;
        this.startTick = this.ticker.read();
        return this;
    }
    @CanIgnoreReturnValue
    public 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 对象统计多段代码的执行时间,也可以通过指定时间类型直接统计出对应的时间间隔,比如我们可以指定时间的统计单位,如秒、毫秒、纳秒等类型。

相关文章
|
14天前
|
数据挖掘 Python
🚀告别繁琐!Python I/O管理实战,文件读写效率飙升的秘密
在日常编程中,高效的文件I/O管理对提升程序性能至关重要。Python通过内置的`open`函数及丰富的库简化了文件读写操作。本文从基本的文件读写入手,介绍了使用`with`语句自动管理文件、批量读写以减少I/O次数、调整缓冲区大小、选择合适编码格式以及利用第三方库(如pandas和numpy)等技巧,帮助你显著提升文件处理效率,让编程工作更加高效便捷。
30 0
|
3月前
|
安全 Python
告别低效编程!Python线程与进程并发技术详解,让你的代码飞起来!
【7月更文挑战第9天】Python并发编程提升效率:**理解并发与并行,线程借助`threading`模块处理IO密集型任务,受限于GIL;进程用`multiprocessing`实现并行,绕过GIL限制。示例展示线程和进程创建及同步。选择合适模型,注意线程安全,利用多核,优化性能,实现高效并发编程。
58 3
|
27天前
|
数据采集 SQL JSON
《花100块做个摸鱼小网站! 》第五篇—通过xxl-job定时获取热搜数据
本文介绍了使用XXL-Job组件优化热搜数据定时更新的方法,实现了包括阿里云服务器部署、代码库下载、表结构初始化及启动等步骤,并详细展示了如何通过注解配置爬虫任务。文中通过具体示例(如抖音热搜)展示了如何将`@Scheduled`注解替换为`@XxlJob`注解,实现更灵活的任务调度。此外,还优化了前端展示,增加了热搜更新时间显示,并提供了B站热搜爬虫的实现方案。通过这些改进,使得热搜组件不仅功能完善,而且更加美观实用。详细代码可在作者提供的代码仓库中查看。
22 6
|
2月前
|
缓存 JavaScript 前端开发
前端10种火火火火的优化代码性能方法!避免代码跑起来像蜗牛!
前端10种火火火火的优化代码性能方法!避免代码跑起来像蜗牛!
|
5月前
|
消息中间件 前端开发 关系型数据库
🤔️测试问我:为啥阅读量计数这么简单的功能你都能写出bug?
🤔️测试问我:为啥阅读量计数这么简单的功能你都能写出bug?
|
10月前
|
测试技术 Go
【测试平台系列】第一章 手撸压力机(七)- 使用gin
今天,我们使用gin框架将压力机做成一个web服务后端。 我们引入gin框架:
【测试平台系列】第一章 手撸压力机(七)- 使用gin
|
存储 索引 容器
灰太狼系列—打地鼠(内含源码) inscode中的直观运行
灰太狼系列—打地鼠(内含源码) inscode中的直观运行
|
数据采集 搜索推荐 小程序
编程新手:看懂很多示例,却依然写不好一个程序
当然题目本身难度不高,和我们公众号【每周一坑】栏目里的题相比,这个算是小 case 了。不过如果你是一个刚刚接触编程不久,才掌握条件判断、循环、列表的新手来说,还是有点小挑战的。
|
监控 Java Go
Go并发调度进阶-GMP初始化,最难啃的有时候耐心看完还是很简单的
Go并发调度进阶-GMP初始化,最难啃的有时候耐心看完还是很简单的