java中是否有命令来测量执行时间?

时间:2011-03-29 11:22:13

标签: java command-line execution-time

java中是否有命令来测量执行时间?

这样的东西
System.out.println(execution.time);

在代码的末尾。

9 个答案:

答案 0 :(得分:7)

以下是关于如何做到这一点的complete and little modified example

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");
  }
}

答案 1 :(得分:3)

您可以使用System.currentTimeMillis()轻松自行实现:

final long start = System.currentTimeMillis();
executeLongRunningTask();
final long durationInMilliseconds = System.currentTimeMillis()-start;
System.out.println("executeLongRunningTask() took " + durationInMilliseconds + "ms.");

或者(特别是如果您的任务运行时间不长),您可能希望使用System.nanoTime()。请注意,与currentTimeMillis()的工作方式相反,nanoTime()返回的值相对于某个指定时间。这意味着nanoTime()只能用于衡量时间跨度,不能用于识别某些特定时间点。

答案 2 :(得分:2)

您可以运行探查器,或使用两次调用System.currentTimeMillis()

的差异

像这样:

long start = System.currentTimeMillis();
....
doSomething();
....
long end = System.currentTimeMillis();

System.out.println("Execution time was "+(end-start)+" ms.");

答案 3 :(得分:2)

最简单的方法是在代码执行之前和之后使用System.currentTimeMillis()。 Joda-Time有更复杂的版本:http://joda-time.sourceforge.net/

答案 4 :(得分:1)

如果您想了解有关测量内容的更多详细信息,我强烈建议您使用JMX,尤其是ThreadMXBean:http://download.oracle.com/javase/6/docs/api/java/lang/management/ThreadMXBean.html

代码示例:

ThreadMXBean bean = ManagementFactory.getThreadMXBean( );
if (bean.isCurrentThreadCpuTimeSupported()) {
    long cpuTime = bean.getCurrentThreadCpuTime( );
}
long userTime = bean.getCurrentThreadUserTime( );

此处提供了代码示例的完整解释: http://nadeausoftware.com/articles/2008/03/java_tip_how_get_cpu_and_user_time_benchmarking

答案 5 :(得分:1)

使用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);
  }
}

答案 6 :(得分:1)

Apache Commons库有StopWatch类,Spring也有StopWatch

答案 7 :(得分:0)

您可以设计一个控件抽象time,它将参数作为要执行的操作,并测量并打印执行它所需的时间。

<强>代码:

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

答案 8 :(得分:0)

我喜欢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";
  }
}