Java统计代码的执行时间的常见方法总结
在日常开发中经常需要测试一些代码的执行时间,但又不想使用向 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;
@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 对象统计多段代码的执行时间,也可以通过指定时间类型直接统计出对应的时间间隔,比如我们可以指定时间的统计单位,如秒、毫秒、纳秒等类型。
方法补充
在 Java 中统计代码执行时间有多种方法,从简单的基础 API 到功能丰富的工具类,各有适用场景。下面介绍几种最常用的方式,并给出示例代码和注意事项。
使用 System.currentTimeMillis()(毫秒级)
最简单、最直接的方法,返回当前时间与 1970-01-01 UTC 的毫秒差值。
long start = System.currentTimeMillis();
// 待测代码
Thread.sleep(100);
long end = System.currentTimeMillis();
System.out.println("执行耗时:" + (end - start) + " ms");优点:
- 简单易用,无需额外依赖。
- 适合粗略测量(毫秒级精度)。
缺点:
- 受系统时间调整影响(如手动修改系统时间会导致结果错误)。
- 精度有限(毫秒级,无法测量极短时间)。
使用 System.nanoTime()(纳秒级,推荐)
返回正在运行的 Java 虚拟机的高精度时间源,不受系统时间调整影响,适合测量短时间间隔。
long start = System.nanoTime();
// 待测代码
Thread.sleep(100);
long end = System.nanoTime();
System.out.println("执行耗时:" + (end - start) / 1_000_000.0 + " ms");优点:
- 高精度(通常可达纳秒级)。
- 不受系统时钟修改影响,是测量代码执行时间的首选。
缺点:不能用于计算绝对时间(只适合测量时间差)。
使用 Instant 与 Duration(Java 8+,更可读)
使用 java.time.Instant 记录时间点,java.time.Duration 计算差值。
import java.time.Duration;
import java.time.Instant;
Instant start = Instant.now();
// 待测代码
Thread.sleep(100);
Instant end = Instant.now();
Duration duration = Duration.between(start, end);
System.out.println("执行耗时:" + duration.toMillis() + " ms");优点:
- 代码语义清晰,可读性好。
Duration提供丰富的单位转换(纳秒、毫秒、秒等)。
缺点:底层依赖系统时钟,与 System.currentTimeMillis() 类似,受系统时间调整影响。
使用 Spring 的 StopWatch(方便管理多个任务)
若项目中已使用 Spring,可以利用 org.springframework.util.StopWatch,支持多任务计时、漂亮输出。
import org.springframework.util.StopWatch;
StopWatch stopWatch = new StopWatch();
stopWatch.start("task1");
// 任务1代码
Thread.sleep(100);
stopWatch.stop();
stopWatch.start("task2");
// 任务2代码
Thread.sleep(50);
stopWatch.stop();
System.out.println(stopWatch.prettyPrint());输出示例:
StopWatch '': running time = 150 ms
---------------------------------------------
ms % Task name
---------------------------------------------
00100 067% task1
00050 033% task2
优点:
- 支持多个任务、任务名、分阶段统计。
- 输出格式美观,适合性能分析。
缺点:需要引入 Spring 框架(或单独使用 spring-core)。
使用 Apache Commons Lang 的 StopWatch
不依赖 Spring 时可使用 Apache Commons Lang 3 的 StopWatch。
import org.apache.commons.lang3.time.StopWatch;
StopWatch watch = new StopWatch();
watch.start();
// 待测代码
Thread.sleep(100);
watch.stop();
System.out.println("耗时:" + watch.getTime() + " ms");优点:
- 轻量级,仅依赖
commons-lang3。 - 支持
split()、suspend()等更细粒度的控制。
缺点:需要额外引入依赖。
JMH(Java Microbenchmark Harness)—— 专业的基准测试工具
当需要精准、可靠地测量微秒级性能、避免 JVM 优化干扰时,应使用 JMH。例如测试某个算法的吞吐量。
import org.openjdk.jmh.annotations.*;
@State(Scope.Thread)
@BenchmarkMode(Mode.AverageTime)
@OutputTimeUnit(TimeUnit.NANOSECONDS)
public class MyBenchmark {
@Benchmark
public void testMethod() {
// 待测代码
}
}运行方式:
mvn clean install java -jar target/benchmarks.jar
优点:
- 自动处理 JVM 预热、死代码消除、黑盒优化等问题。
- 提供多种测量模式(吞吐量、平均时间、采样时间等)。
- 结果统计信息全面(均值、误差、百分位数等)。
缺点:
- 学习曲线较陡,配置相对复杂。
- 不适合简单的“一次性”计时。
总结与对比
| 方法 | 精度 | 是否受系统时间调整 | 适用场景 |
|---|---|---|---|
System.currentTimeMillis() | 毫秒 | 是 | 粗略测量,简单日志 |
System.nanoTime() | 纳秒(高精度) | 否 | 绝大多数计时需求推荐 |
Instant + Duration | 毫秒(实际同系统时间) | 是 | 追求可读性,且不受系统时间影响不重要时 |
Spring StopWatch | 毫秒 | 否(使用nanoTime) | 多任务分段计时,输出美观 |
Apache Commons StopWatch | 毫秒 | 否 | 轻量级,需要额外库 |
| JMH | 极高(纳秒级) | 否 | 微基准测试,JVM 性能调优 |
最佳实践:
- 对于单元测试或简单性能日志,使用
System.nanoTime()即可满足绝大部分需求。 - 若需要同时测量多个阶段或输出美观报告,选用 Spring 或 Apache Commons 的
StopWatch。 - 编写正式的性能基准(如方法优化对比),务必使用 JMH,避免 JVM 优化带来的虚假结果。
最后,测量代码执行时间时,要注意:
- JVM 存在预热(Just-In-Time 编译),第一次执行往往较慢,建议多次运行取平均值。
- 测量时间过短的代码(< 1ms)容易受操作系统线程调度影响,应循环多次测量并求平均。
以上就是Java统计代码的执行时间的常见方法总结的详细内容,更多关于Java统计代码执行时间的资料请关注脚本之家其它相关文章!
相关文章
SpringCloud Gateway使用redis实现动态路由的方法
这篇文章主要介绍了SpringCloud Gateway使用redis实现动态路由的方法,本文给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下2021-01-01
idea maven依赖引入失效无法正常导入依赖问题的解决方法
有时候idea导入一个新项目,或者pom文件修改(新增)了依赖,pom文件和代码会报红,提示依赖包不存在,下面这篇文章主要给大家介绍了关于idea maven依赖引入失效无法正常导入依赖问题的解决方法,需要的朋友可以参考下2023-04-04


最新评论