java中有没有一个命令可以测量执行时间?

发布于 2024-10-28 18:30:26 字数 119 浏览 1 评论 0原文

java中有没有一个命令可以测量执行时间?

内容。

System.out.println(execution.time);

类似于代码末尾的

Is there a command in java to measure the execution time ?

Something like

System.out.println(execution.time);

in the end of the code.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(9

眉目亦如画i 2024-11-04 18:30:26

这是一个关于如何做到这一点的完整且稍作修改的示例

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

Here is a complete and little modified example on 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");
  }
}
乖乖 2024-11-04 18:30:26

您可以使用 自行轻松实现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()只能用于测量时间跨度,而不能用于识别某个特定的时间点。

You can easily implement that yourself using 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 not relative to some specified time. This means that nanoTime() can only be used to measure time spans and can't be used to identify some specifiy point in time.

音盲 2024-11-04 18:30:26

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

如下所示:

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

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

You could run a profiler, or use the difference of two calls to System.currentTimeMillis()

Like this :

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

System.out.println("Execution time was "+(end-start)+" ms.");
死开点丶别碍眼 2024-11-04 18:30:26

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

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/

七度光 2024-11-04 18:30:26

如果您想了解有关测量内容的更多详细信息,我强烈建议您使用 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

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

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

听风吹 2024-11-04 18:30:26

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

Use the ThreadMXBean for more detailed timing:

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);
  }
}
帅冕 2024-11-04 18:30:26

Apache Commons 库有 StopWatch类,Spring还有 StopWatch

Apache Commons library has StopWatch class and Spring also has StopWatch.

划一舟意中人 2024-11-04 18:30:26

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

代码:

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

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.

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
靑春怀旧 2024-11-04 18:30:26

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

I liked the class example of RoflcoptrException.
I rewrote it to its essentials:

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";
  }
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文