java java中是否有测量执行时间的命令?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5471700/
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
Is there a command in java to measure the execution time?
提问by user680406
Is there a command in java to measure the execution time ?
java中是否有测量执行时间的命令?
Something like
就像是
System.out.println(execution.time);
in the end of the code.
在代码的最后。
回答by RoflcoptrException
Here is a complete and little modified exampleon how you could do that:
这是一个关于如何做到这一点的完整且稍加修改的示例:
public class ExecutionTimer {
private long start;
private long end;
public ExecutionTimer() {
reset();
start = System.currentTimeMillis();
}
public void end() {
end = System.currentTimeMillis();
}
public long duration(){
return (end-start);
}
public void reset() {
start = 0;
end = 0;
}
public static void main(String s[]) {
// simple example
ExecutionTimer t = new ExecutionTimer();
for (int i = 0; i < 80; i++){
System.out.print(".");
}
t.end();
System.out.println("\n" + t.duration() + " ms");
}
}
回答by Joachim Sauer
You can easily implement that yourself using System.currentTimeMillis()
:
您可以使用System.currentTimeMillis()
以下方法轻松实现:
final long start = System.currentTimeMillis();
executeLongRunningTask();
final long durationInMilliseconds = System.currentTimeMillis()-start;
System.out.println("executeLongRunningTask() took " + durationInMilliseconds + "ms.");
Alternatively (especially if your task doesn't run as long), you might want to use System.nanoTime()
. Note that contrary to how currentTimeMillis()
works, the value returned by nanoTime()
is notrelative to some specified time. This means that nanoTime()
can only be used to measure time spansand can't be used to identify some specifiy point in time.
或者(特别是如果您的任务运行时间不长),您可能希望使用System.nanoTime()
. 需要注意的是违背了如何currentTimeMillis()
工作,返回的值nanoTime()
是不是相对于某一指定的时间。这意味着nanoTime()
只能用于测量时间跨度,不能用于识别某些特定的时间点。
回答by sgokhales
You could run a profiler, or use the difference of two calls to System.currentTimeMillis()
您可以运行分析器,或使用两次调用的差异 System.currentTimeMillis()
Like this :
像这样 :
long start = System.currentTimeMillis();
....
doSomething();
....
long end = System.currentTimeMillis();
System.out.println("Execution time was "+(end-start)+" ms.");
回答by Justin Thomas
Easiest way is to use System.currentTimeMillis() before and after the code executing. Joda-Time has more sophisticated versions of that: http://joda-time.sourceforge.net/
最简单的方法是在代码执行前后使用 System.currentTimeMillis()。Joda-Time 有更复杂的版本:http: //joda-time.sourceforge.net/
回答by Denis R.
If you want to have more details on what you measure, I strongly suggest you use JMX especially ThreadMXBean : http://download.oracle.com/javase/6/docs/api/java/lang/management/ThreadMXBean.html
如果您想了解有关测量内容的更多详细信息,我强烈建议您使用 JMX,尤其是 ThreadMXBean:http: //download.oracle.com/javase/6/docs/api/java/lang/management/ThreadMXBean.html
Code sample :
代码示例:
ThreadMXBean bean = ManagementFactory.getThreadMXBean( );
if (bean.isCurrentThreadCpuTimeSupported()) {
long cpuTime = bean.getCurrentThreadCpuTime( );
}
long userTime = bean.getCurrentThreadUserTime( );
A quite complete explanation with code samples is available here : http://nadeausoftware.com/articles/2008/03/java_tip_how_get_cpu_and_user_time_benchmarking
一个非常完整的代码示例解释可以在这里找到:http: //nadeausoftware.com/articles/2008/03/java_tip_how_get_cpu_and_user_time_benchmarking
回答by user85421
Use the ThreadMXBean for more detailed timing:
使用 ThreadMXBean 获取更详细的计时:
public class Timer {
static {
// needed to request 1ms timer interrupt period
// http://discuss.joelonsoftware.com/default.asp?joel.3.642646.9
Thread thread = new Thread(new Runnable() {
@Override
public void run() {
try {
Thread.sleep(Integer.MAX_VALUE); (Windows NT)
} catch (InterruptedException ignored) {
}
}
});
thread.setName("Timer");
thread.setDaemon(true);
thread.start();
}
private final ThreadMXBean threadMX = ManagementFactory.getThreadMXBean();
private final long elapsedStart;
private final long cpuStart;
private final long userStart;
public Timer() {
cpuStart = threadMX.getCurrentThreadCpuTime();
userStart = threadMX.getCurrentThreadUserTime();
elapsedStart = System.nanoTime();
}
public void times() {
long elapsed = elapsedStart - System.nanoTime();
long cpu = cpuStart - threadMX.getCurrentThreadCpuTime();
long user = userStart - threadMX.getCurrentThreadUserTime();
System.out.printf("elapsed=%-8.3f cpu=%-8.3f user=%-8.3f [seconds]",
elapsed/1.0e9, cpu/1.0e9, user/1.0e9);
}
}
回答by pingw33n
回答by missingfaktor
You can design a control abstraction time
that takes as parameter an action to be performed and measures and prints the time required to execute it.
您可以设计一个控制抽象time
,将要执行的操作作为参数,并测量和打印执行它所需的时间。
Code:
代码:
interface Action<A> {
public A perform();
}
class Timer {
public static <A> A time(final String description, final Action<A> action) {
final long start = System.nanoTime();
final A result = action.perform();
final long end = System.nanoTime();
System.out.println(description + " - Time elapsed: " + (end - start) +"ns");
return result;
}
}
class Main {
public static void main(final String[] args) {
final int factorialOf5 = Timer.time("Calculating factorial of 5",
new Action<Integer>() {
public Integer perform() {
int result = 1;
for(int i = 2; i <= 5; i++) {
result *= i;
}
return result;
}
}
);
System.out.println("Result: " + factorialOf5);
}
}
// Output:
// Calculating factorial of 5 - Time elapsed: 782052ns
// Result: 120
回答by Herke Jan
I liked the class example of RoflcoptrException. I rewrote it to its essentials:
我喜欢 RoflcoptrException 的类示例。我把它改写成它的本质:
public class ExecutionTimer {
private long start;
public ExecutionTimer() {
restart();
}
public void restart() {
start = System.currentTimeMillis();
}
public long time(){
long end = System.currentTimeMillis();
return (end-start);
}
public String toString() {
return "Time="+time()+" ms";
}
}