我如何计算Java方法执行所需的时间?
我如何计算Java方法执行所需的时间?
nanoTime()
方法,而不是currentTimeMillis()
方法:long startTime = System.nanoTime();
myCall();
long stopTime = System.nanoTime();
System.out.println(stopTime - startTime);
在Java 8中(输出格式为ISO-8601):
Instant start = Instant.now();
Thread.sleep(63553);
Instant end = Instant.now();
System.out.println(Duration.between(start, end)); // prints PT1M3.553S
Guava 计时器:
Stopwatch stopwatch = Stopwatch.createStarted();
myCall();
stopwatch.stop(); // optional
System.out.println("Time elapsed: "+ stopwatch.elapsed(TimeUnit.MILLISECONDS));
您可以在之前和之后获取时间戳快照,然后重复多次实验以平均结果。也有一些分析工具可以为您完成这项任务。
使用System.currentTimeMillis()
class TimeTest1 {
public static void main(String[] args) {
long startTime = System.currentTimeMillis();
long total = 0;
for (int i = 0; i < 10000000; i++) {
total += i;
}
long stopTime = System.currentTimeMillis();
long elapsedTime = stopTime - startTime;
System.out.println(elapsedTime);
}
}
使用StopWatch类
您可以使用这个StopWatch
类,在方法之前调用start()
,在方法之后调用stop()
。
class TimeTest2 {
public static void main(String[] args) {
Stopwatch timer = new Stopwatch().start();
long total = 0;
for (int i = 0; i < 10000000; i++) {
total += i;
}
timer.stop();
System.out.println(timer.getElapsedTime());
}
}
请参见此处(已存档)。
应用程序性能应用程序
性能概要文件方法级CPU性能(执行时间)。您可以选择对整个应用程序或应用程序的一部分进行分析。
请参见此处。
currentTimeMillis
而不是 nanoTime
。为了了解预热时间和结果之间的差异,通常会在外部加入循环以重复计时五次。请注意,您可能不希望在被测试的方法中包含计时器代码。 - Tom Hawtin - tackline有了这个,您可以通过以下方式计算方法的时间:
long start = System.currentTimeMillis();
class.method();
long time = System.currentTimeMillis() - start;
如果你开发 Android 应用程序,你应该尝试使用 TimingLogger
类。
请查看这些描述如何使用 TimingLogger
辅助类的文章:
public class MyService {
public void doSomething() {
for (int i = 1; i < 10000; i++) {
System.out.println("i=" + i);
}
}
}
为了避免更改服务,您可以编写自己的方法拦截器:public class ServiceMethodInterceptor implements MethodInterceptor {
public Object invoke(MethodInvocation methodInvocation) throws Throwable {
long startTime = System.currentTimeMillis();
Object result = methodInvocation.proceed();
long duration = System.currentTimeMillis() - startTime;
Method method = methodInvocation.getMethod();
String methodName = method.getDeclaringClass().getName() + "." + method.getName();
System.out.println("Method '" + methodName + "' took " + duration + " milliseconds to run");
return null;
}
}
还有一些针对Java的开源API可供使用,例如BTrace。 或者像@bakkal和@Saikikos建议的那样使用Netbeans分析器。 谢谢。
如所提出的nanoTime()在短时间尺度上非常精确。 当需要这种精度时,您需要注意您真正测量的内容。 特别是不要测量nanotime调用本身。
long start1 = System.nanoTime();
// maybe add here a call to a return to remove call up time, too.
// Avoid optimization
long start2 = System.nanoTime();
myCall();
long stop = System.nanoTime();
long diff = stop - 2*start2 + start1;
System.out.println(diff + " ns");
顺便说一下,由于以下原因,您将为相同的调用测量不同的值:
Nanotime实际上甚至不适用于经过的时间,因为它比currentTimeMillis漂移得更多。此外,nanotime倾向于在精度方面提供过度的精确性,而牺牲准确性。因此,它高度不一致,并需要改进。
对于任何时间测量过程,currentTimeMillis(虽然几乎同样糟糕),在平衡准确性和精度方面表现更好。