如何获得方法的执行时间? 是否有Timer实用程序类来计时任务所需的时间等?
在谷歌上的大多数搜索都返回调度线程和任务的计时器的结果,这不是我想要的。
如何获得方法的执行时间? 是否有Timer实用程序类来计时任务所需的时间等?
在谷歌上的大多数搜索都返回调度线程和任务的计时器的结果,这不是我想要的。
当前回答
你可以使用spring core项目中的stopwatch类:
代码:
StopWatch stopWatch = new StopWatch()
stopWatch.start(); //start stopwatch
// write your function or line of code.
stopWatch.stop(); //stop stopwatch
stopWatch.getTotalTimeMillis() ; ///get total time
Documentation for Stopwatch: Simple stop watch, allowing for timing of a number of tasks, exposing total running time and running time for each named task. Conceals use of System.currentTimeMillis(), improving the readability of application code and reducing the likelihood of calculation errors. Note that this object is not designed to be thread-safe and does not use synchronization. This class is normally used to verify performance during proof-of-concepts and in development, rather than as part of production applications.
其他回答
JEP 230:微基准测试套件
供参考,JEP 230: Microbenchmark Suite是一个OpenJDK项目,用于:
向JDK源代码中添加一套基本的微基准测试,使开发人员可以轻松地运行现有的微基准测试和创建新的微基准测试。
这个特性是在Java 12中出现的。
Java微基准测试工具(JMH)
对于Java的早期版本,请查看JEP 230所基于的Java Microbenchmark Harness (JMH)项目。
也可以实现定时器接口,并在类的任何方法上执行
import java.util.function.*;
public interface Timer {
default void timeIt(Runnable r) {
timeIt(() -> { r.run(); return 0;});
}
default <S,T> T timeIt(Function<S,T> fun, S arg) {
long start = System.nanoTime();
T result = fun.apply(arg);
long stop = System.nanoTime();
System.out.println("Time: " + (stop-start)/1000000.0 + " msec");
return result;
}
default <T> T timeIt(Supplier<T> s) {
return timeIt(obj -> s.get(), null);
}
}
用法:
class MyClass implements Timer ..
timeIt(this::myFunction);
在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());
使用AOP/AspectJ和来自jcabi-aspects的@Loggable注释,你可以简单而紧凑地完成:
@Loggable(Loggable.DEBUG)
public String getSomeResult() {
// return some value
}
对该方法的每个调用都将发送到SLF4J日志记录工具,具有DEBUG日志记录级别。每个日志消息都将包括执行时间。
如果你想要时间
long start_time = System.currentTimeMillis();
object.method();
long end_time = System.currentTimeMillis();
long execution_time = end_time - start_time;