如何获得方法的执行时间? 是否有Timer实用程序类来计时任务所需的时间等?
在谷歌上的大多数搜索都返回调度线程和任务的计时器的结果,这不是我想要的。
如何获得方法的执行时间? 是否有Timer实用程序类来计时任务所需的时间等?
在谷歌上的大多数搜索都返回调度线程和任务的计时器的结果,这不是我想要的。
当前回答
这里有很多有效的答案,它们都是在方法中实现的。为了制作一个通用的计时方法,我通常有一个timing类,它由以下内容组成。
public record TimedResult<T>(T result, Duration duration) {}
public static Duration time(Runnable r) {
var s = Instant.now();
r.run();
var dur = Duration.between(s, Instant.now());
return dur;
}
public static <T> TimedResult<T> time(Callable<T> r) throws Exception {
var s = Instant.now();
T res = r.call();
var dur = Duration.between(s, Instant.now());
return new TimedResult<>(res, dur);
}
这足够通用,可以传递Runnable或Callable对象。
Duration result = Timing.time(() -> {
// do some work.
});
TimedResult<String> result = Timing.time(() -> {
// do some work.
return "answer";
});
Duration timeTaken = result.duration();
String answer = result.result();
其他回答
如果你想要时间
long start_time = System.currentTimeMillis();
object.method();
long end_time = System.currentTimeMillis();
long execution_time = end_time - start_time;
JEP 230:微基准测试套件
供参考,JEP 230: Microbenchmark Suite是一个OpenJDK项目,用于:
向JDK源代码中添加一套基本的微基准测试,使开发人员可以轻松地运行现有的微基准测试和创建新的微基准测试。
这个特性是在Java 12中出现的。
Java微基准测试工具(JMH)
对于Java的早期版本,请查看JEP 230所基于的Java Microbenchmark Harness (JMH)项目。
加油,伙计们!没有人提到用番石榴来做这件事(可以说是很棒):
import com.google.common.base.Stopwatch;
Stopwatch timer = Stopwatch.createStarted();
//method invocation
LOG.info("Method took: " + timer.stop());
Stopwatch.toString()很好地为测量选择了时间单位。也就是说,如果值很小,它将输出38ns,如果值很长,它将显示5m 3s
甚至更好的:
Stopwatch timer = Stopwatch.createUnstarted();
for (...) {
timer.start();
methodToTrackTimeFor();
timer.stop();
methodNotToTrackTimeFor();
}
LOG.info("Method took: " + timer);
注意:谷歌Guava需要Java 1.6+
在Spring框架中我们有一个叫做StopWatch的调用(org。Spring framework。util。StopWatch)
//measuring elapsed time using Spring StopWatch
StopWatch watch = new StopWatch();
watch.start();
for(int i=0; i< 1000; i++){
Object obj = new Object();
}
watch.stop();
System.out.println("Total execution time to create 1000 objects in Java using StopWatch in millis: "
+ watch.getTotalTimeMillis());
对于java 8+,另一种可能的解决方案(更通用,函数风格,没有方面)可能是创建一些实用程序方法,将代码作为参数接受
public static <T> T timed (String description, Consumer<String> out, Supplier<T> code) {
final LocalDateTime start = LocalDateTime.now ();
T res = code.get ();
final long execTime = Duration.between (start, LocalDateTime.now ()).toMillis ();
out.accept (String.format ("%s: %d ms", description, execTime));
return res;
}
调用代码可以是这样的smth:
public static void main (String[] args) throws InterruptedException {
timed ("Simple example", System.out::println, Timing::myCode);
}
public static Object myCode () {
try {
Thread.sleep (1500);
} catch (InterruptedException e) {
e.printStackTrace ();
}
return null;
}