测量 Java 方法的执行时间
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3382954/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Measure execution time for a Java method
提问by Renuka
How do I calculate the time taken for the execution of a method in Java?
如何计算在 Java 中执行方法所花费的时间?
回答by Renuka
Check this: System.currentTimeMillis.
检查这个:System.currentTimeMillis。
With this you can calculate the time of your method by doing:
有了这个,您可以通过执行以下操作来计算您的方法的时间:
long start = System.currentTimeMillis();
class.method();
long time = System.currentTimeMillis() - start;
回答by bakkal
You can take timestamp snapshots before and after, then repeat the experiments several times to average to results. There are also profilers that can do this for you.
您可以在前后拍摄时间戳快照,然后多次重复实验以求平均结果。也有分析器可以为您执行此操作。
From "Java Platform Performance: Strategies and Tactics" book:
来自“Java 平台性能:策略与策略”一书:
With System.currentTimeMillis()
使用 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);
}
}
With a StopWatch class
使用秒表类
You can use this StopWatch
class, and call start()
and stop
before and after the method.
您可以使用这个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());
}
}
See here.
见这里。
NetBeans Profiler:
NetBeans 分析器:
Application Performance Application
Performance profiles method-level CPU performance (execution time). You can choose to profile the entire application or a part of the application.
应用性能应用
性能配置文件方法级 CPU 性能(执行时间)。您可以选择分析整个应用程序或应用程序的一部分。
See here.
见这里。
回答by Vitalii Fedorenko
To be more precise, I would use nanoTime()
method rather than currentTimeMillis()
:
更准确地说,我会使用nanoTime()
方法而不是currentTimeMillis()
:
long startTime = System.nanoTime();
myCall();
long stopTime = System.nanoTime();
System.out.println(stopTime - startTime);
In Java 8 (output format is ISO-8601):
在 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 = Stopwatch.createStarted();
myCall();
stopwatch.stop(); // optional
System.out.println("Time elapsed: "+ stopwatch.elapsed(TimeUnit.MILLISECONDS));
回答by duffymo
You might want to think about aspect-oriented programming. You don't want to litter your code with timings. You want to be able to turn them off and on declaratively.
您可能想考虑面向方面的编程。您不想在时间上乱扔代码。您希望能够以声明方式关闭和打开它们。
If you use Spring, take a look at their MethodInterceptorclass.
如果您使用 Spring,请查看他们的MethodInterceptor类。
回答by stefan bachert
As proposed nanoTime () is very precise on short time scales. When this precision is required you need to take care about what you really measure. Especially not to measure the nanotime call itself
正如所提出的,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");
By the way, you will measure different values for the same call due to
顺便说一句,由于
- other load on your computer (background, network, mouse movement, interrupts, task switching, threads)
- cache fillings (cold, warm)
- jit compiling (no optimization, performance hit due to running the compiler, performance boost due to compiler (but sometimes code with jit is slower than without!))
- 计算机上的其他负载(背景、网络、鼠标移动、中断、任务切换、线程)
- 缓存填充物(冷,热)
- jit 编译(没有优化,由于运行编译器而导致性能下降,由于编译器而导致性能提升(但有时使用 jit 的代码比不使用时要慢!))
回答by kinshuk4
If you are currently writing the application, than the answer is to use System.currentTimeMillisor System.nanoTimeserve the purpose as pointed by people above.
如果您当前正在编写应用程序,那么答案是使用System.currentTimeMillis或System.nanoTime服务于上面人们指出的目的。
But if you have already written the code, and you don't want to change it its better to use Spring's method interceptors. So for instance your service is :
但是如果您已经编写了代码,并且不想更改它,那么最好使用 Spring 的方法拦截器。例如,您的服务是:
public class MyService {
public void doSomething() {
for (int i = 1; i < 10000; i++) {
System.out.println("i=" + i);
}
}
}
To avoid changing the service, you can write your own method interceptor:
为避免更改服务,您可以编写自己的方法拦截器:
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;
}
}
Also there are open source APIs available for Java, e.g. BTrace. or Netbeans profiler as suggested above by @bakkal and @Saikikos. Thanks.
还有一些可用于 Java 的开源 API,例如BTrace。或@bakkal 和@Saikikos 上面建议的 Netbeans 分析器。谢谢。
回答by sarvesh
Nanotime is in fact not even good for elapsed time because it drifts away signficantly more than currentTimeMillis. Furthermore nanotime tends to provide excessive precision at the expense of accuracy. It is therefore highly inconsistent,and needs refinement.
Nanotime 实际上甚至对流逝的时间都没有好处,因为它比 currentTimeMillis 漂移得更多。此外,纳米时间往往会以牺牲准确性为代价提供过高的精度。因此它高度不一致,需要改进。
For any time measuring process,currentTimeMillis (though almost as bad), does better in terms of balancing accuracy and precision.
对于任何时间测量过程,currentTimeMillis(尽管几乎同样糟糕)在平衡精度和精度方面做得更好。
回答by JJD
In case you develop applications for Androidyou should try out the TimingLogger
class.
Take a look at these articles describing the usage of the TimingLogger
helper class:
如果您为Android开发应用程序,您应该尝试该TimingLogger
课程。
看看这些描述TimingLogger
helper 类用法的文章:
- Measuring performance in the Android SDK(27.09.2010)
- Discovering the Android API - Part 1(03.01.2017)
- 在 Android SDK 中测量性能(27.09.2010)
- 发现 Android API - 第 1 部分(03.01.2017)