我想知道在一个大方法中运行许多代码段需要多长时间。
我用
System.nanoTime()
来记录时间戳。然后,我减去两个时间戳,例如nano2-nano1
,以获得执行持续时间。
public static void largeMehod() {
long nano1 = System.nanoTime();
System.out.println("it takes a long time ~N sec");
long nano2 = System.nanoTime();
System.out.println("it takes a long time ~N sec");
long nano3 = System.nanoTime();
System.out.println("it takes a long time ~N sec");
long nano4 = System.nanoTime();
System.out.printf("put together, 1-2=%s 2-3=%s 3-4=%s%n", nano2 - nano1, nano3 - nano2, nano4 - nano3);
}
问题在这里:
用番石榴秒表:
public static void largeMehod() {
Stopwatch stopwatch = Stopwatch.createStarted();
System.out.println("it takes a long time ~N sec");
stopwatch.stop();
Duration elapse12 = stopwatch.elapsed();
stopwatch.reset();
stopwatch.start();
System.out.println("it takes a long time ~N sec");
stopwatch.stop();
Duration elapsed23 = stopwatch.elapsed();
stopwatch.reset();
stopwatch.start();
System.out.println("it takes a long time ~N sec");
stopwatch.stop();
Duration elapsed34 = stopwatch.elapsed();
System.out.printf("put together, 1-2=%s 2-3=%s 3-4=%s%n", elapse12, elapsed23, elapsed34);
}
它确实对命名变量有一点帮助,但使用
.reset()
和 .stop()
方法调用看起来更混乱。
你能给我一些建议吗?任何建议表示赞赏。
您可以将方法链接在一起:
stopwatch.reset().start()
。另外,您无需在拨打elapsed()
之前停下来。所以你可以像这样缩短你的代码:
stopwatch.reset().start();
System.out.println("it takes a long time ~N sec");
Duration elapsed23 = stopwatch.elapsed();
您甚至可以创建一个运行一些代码并对其计时的方法:
public static Duration measureTime(Callable<Void> code) {
Stopwatch stopwatch = Stopwatch.createStarted();
code.call();
return stopwatch.elapsed();
}
并像这样使用它:
Duration elapsed23 = measureTime(() -> {
System.out.println("it takes a long time ~N sec");
});
如果您在大型应用程序中重新执行此操作,则应考虑使用 Open Telemetry。这将是“专业”方式,但这是一个非常陡峭的学习曲线,并且还需要在部署时具备一定的基础设施,因此只有当您已经在使用软件查看指标时才应该这样做。