如何计时java
计时 Java 程序的方法
使用 System.currentTimeMillis()
通过获取程序开始和结束时的系统时间差来计时。

long startTime = System.currentTimeMillis();
// 待计时代码
for (int i = 0; i < 1000000; i++) {
// 模拟耗时操作
}
long endTime = System.currentTimeMillis();
long duration = endTime - startTime;
System.out.println("耗时: " + duration + " 毫秒");
使用 System.nanoTime()
适用于高精度计时,如纳秒级测量。

long startTime = System.nanoTime();
// 待计时代码
for (int i = 0; i < 1000000; i++) {
// 模拟耗时操作
}
long endTime = System.nanoTime();
long duration = endTime - startTime;
System.out.println("耗时: " + duration + " 纳秒");
使用 Instant 和 Duration(Java 8+)
java.time 包提供更现代的计时方式。
import java.time.Instant;
import java.time.Duration;
Instant start = Instant.now();
// 待计时代码
for (int i = 0; i < 1000000; i++) {
// 模拟耗时操作
}
Instant end = Instant.now();
Duration duration = Duration.between(start, end);
System.out.println("耗时: " + duration.toMillis() + " 毫秒");
使用 StopWatch(第三方库)
Apache Commons Lang 或 Spring 框架提供 StopWatch 工具类。
import org.apache.commons.lang3.time.StopWatch;
StopWatch stopWatch = new StopWatch();
stopWatch.start();
// 待计时代码
for (int i = 0; i < 1000000; i++) {
// 模拟耗时操作
}
stopWatch.stop();
System.out.println("耗时: " + stopWatch.getTime() + " 毫秒");
注意事项
System.currentTimeMillis()可能受系统时间调整影响,不适合高精度计时。System.nanoTime()适合测量短时间间隔,但不同 JVM 实现可能有差异。- 避免在测量中包含 JVM 预热时间,多次运行取平均值更准确。






