如何获得方法的执行时间? 是否有Timer实用程序类来计时任务所需的时间等?
在谷歌上的大多数搜索都返回调度线程和任务的计时器的结果,这不是我想要的。
如何获得方法的执行时间? 是否有Timer实用程序类来计时任务所需的时间等?
在谷歌上的大多数搜索都返回调度线程和任务的计时器的结果,这不是我想要的。
当前回答
使用分析器(JProfiler, Netbeans profiler, Visual VM, Eclipse profiler等)。您将得到最准确的结果,并且是最少的干扰。它们使用内置的JVM机制进行概要分析,还可以为您提供额外的信息,如堆栈跟踪、执行路径以及必要时更全面的结果。
当使用完全集成的分析器时,对方法进行分析是非常简单的。右击,分析器->添加到根方法。然后像运行测试运行或调试器一样运行剖析器。
其他回答
在Java 8中,你也可以对每个正常的方法做这样的事情:
Object returnValue = TimeIt.printTime(() -> methodeWithReturnValue());
//do stuff with your returnValue
与TimeIt像:
public class TimeIt {
public static <T> T printTime(Callable<T> task) {
T call = null;
try {
long startTime = System.currentTimeMillis();
call = task.call();
System.out.print((System.currentTimeMillis() - startTime) / 1000d + "s");
} catch (Exception e) {
//...
}
return call;
}
}
使用这种方法,您可以在代码的任何地方进行简单的时间测量,而不会破坏它。在这个简单的例子中,我只是打印时间。你可以为TimeIt添加一个开关,例如,在DebugMode中只打印时间。
如果你正在使用函数,你可以这样做:
Function<Integer, Integer> yourFunction= (n) -> {
return IntStream.range(0, n).reduce(0, (a, b) -> a + b);
};
Integer returnValue = TimeIt.printTime2(yourFunction).apply(10000);
//do stuff with your returnValue
public static <T, R> Function<T, R> printTime2(Function<T, R> task) {
return (t) -> {
long startTime = System.currentTimeMillis();
R apply = task.apply(t);
System.out.print((System.currentTimeMillis() - startTime) / 1000d
+ "s");
return apply;
};
}
您可以使用Perf4j。非常酷的实用工具。用法简单
String watchTag = "target.SomeMethod";
StopWatch stopWatch = new LoggingStopWatch(watchTag);
Result result = null; // Result is a type of a return value of a method
try {
result = target.SomeMethod();
stopWatch.stop(watchTag + ".success");
} catch (Exception e) {
stopWatch.stop(watchTag + ".fail", "Exception was " + e);
throw e;
}
更多信息可以在开发者指南中找到
编辑:项目似乎已死
总有一些过时的方法:
long startTime = System.nanoTime();
methodToTime();
long endTime = System.nanoTime();
long duration = (endTime - startTime); //divide by 1000000 to get milliseconds.
使用Java 8的新API中的即时和持续时间,
Instant start = Instant.now();
Thread.sleep(5000);
Instant end = Instant.now();
System.out.println(Duration.between(start, end));
输出,
PT5S
我修改了代码,从正确答案得到的结果在几秒钟内:
long startTime = System.nanoTime();
methodCode ...
long endTime = System.nanoTime();
double duration = (double)(endTime - startTime) / (Math.pow(10, 9));
Log.v(TAG, "MethodName time (s) = " + duration);