Java 代码执行耗时统计:System.currentTimeMillis() 和 Instant 类方法对比

在 Java 开发过程中,我们经常需要统计代码的执行时间,以便了解代码的效率和性能。本文将介绍两种常用的方法来记录代码执行时间,并提供示例代码对比。

1. 使用 System.currentTimeMillis() 方法

System.currentTimeMillis() 方法返回当前时间的毫秒值,我们可以通过记录代码执行的开始时间和结束时间,然后计算二者之差来得到代码执行的耗时。

long startTime = System.currentTimeMillis();

// 执行代码

long endTime = System.currentTimeMillis();
long elapsedTime = endTime - startTime;
System.out.println('代码执行耗时:' + elapsedTime + '毫秒');

2. 使用 Java 8 引入的 Instant 类

Java 8 引入了 java.time 包,其中 Instant 类可以用来表示一个时间点。我们可以使用 Instant.now() 方法获取当前时间,并通过 Duration 类计算两个时间点之间的间隔。

Instant startTime = Instant.now();

// 执行代码

Instant endTime = Instant.now();
Duration elapsedTime = Duration.between(startTime, endTime);
System.out.println('代码执行耗时:' + elapsedTime.toMillis() + '毫秒');

两种方法对比

| 方法 | 优点 | 缺点 | |---|---|---| | System.currentTimeMillis() | 简单易用,不需要引入额外的类 | 精度较低,受系统时间影响 | | Instant | 精度较高,不受系统时间影响 | 需要使用 Java 8 或更高版本 |

总而言之,选择哪种方法取决于你的具体需求。如果需要更高的精度,建议使用 Instant 类;如果只需要简单的计时,System.currentTimeMillis() 方法就足够了。

Java 代码执行耗时统计:System.currentTimeMillis() 和 Instant 类方法对比

原文地址: https://www.cveoy.top/t/topic/nje7 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录