java计时如何实现
使用 System.currentTimeMillis()
在需要计时的代码段前后分别调用 System.currentTimeMillis() 获取当前时间戳,计算差值即为耗时。
long startTime = System.currentTimeMillis();
// 需要计时的代码
long endTime = System.currentTimeMillis();
long duration = endTime - startTime;
System.out.println("耗时:" + duration + "毫秒");
使用 System.nanoTime()
System.nanoTime() 提供更高精度的计时,适用于需要纳秒级精度的场景。
long startTime = System.nanoTime();
// 需要计时的代码
long endTime = System.nanoTime();
long duration = endTime - startTime;
System.out.println("耗时:" + duration + "纳秒");
使用 StopWatch 类(Spring 框架)
Spring 框架提供了 StopWatch 工具类,可以方便地进行分段计时。

StopWatch stopWatch = new StopWatch();
stopWatch.start("任务1");
// 任务1代码
stopWatch.stop();
stopWatch.start("任务2");
// 任务2代码
stopWatch.stop();
System.out.println(stopWatch.prettyPrint());
使用 Java 8 的 Instant 类
Java 8 引入了新的时间 API,可以使用 Instant 进行计时。
Instant start = Instant.now();
// 需要计时的代码
Instant end = Instant.now();
Duration duration = Duration.between(start, end);
System.out.println("耗时:" + duration.toMillis() + "毫秒");
使用 Timer 和 TimerTask
如果需要周期性执行任务并计时,可以使用 Timer 和 TimerTask。

Timer timer = new Timer();
timer.schedule(new TimerTask() {
@Override
public void run() {
System.out.println("定时任务执行时间:" + System.currentTimeMillis());
}
}, 0, 1000); // 延迟0毫秒,每隔1000毫秒执行一次
使用 CompletableFuture 异步计时
对于异步任务,可以使用 CompletableFuture 结合计时功能。
CompletableFuture<Void> future = CompletableFuture.runAsync(() -> {
long start = System.currentTimeMillis();
// 异步任务代码
long duration = System.currentTimeMillis() - start;
System.out.println("异步任务耗时:" + duration + "毫秒");
});
使用 JMH 进行基准测试
对于需要精确性能测试的场景,可以使用 JMH(Java Microbenchmark Harness)工具。
@BenchmarkMode(Mode.AverageTime)
@OutputTimeUnit(TimeUnit.MILLISECONDS)
@State(Scope.Thread)
public class MyBenchmark {
@Benchmark
public void testMethod() {
// 需要测试性能的代码
}
}
每种方法适用于不同场景,System.currentTimeMillis() 和 System.nanoTime() 适合简单计时,StopWatch 适合多任务分段计时,Instant 适合 Java 8 时间 API 集成,Timer 适合周期性任务,CompletableFuture 适合异步任务,JMH 适合专业性能测试。






