【问题标题】:Is there a command in java to measure the execution time?java中是否有测量执行时间的命令?
【发布时间】:2011-03-29 11:22:12
【问题描述】:

java中有没有测量执行时间的命令?

类似

System.out.println(execution.time);

在代码末尾。

【问题讨论】:

    标签: java command-line execution-time


    【解决方案1】:

    这里有一个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");
      }
    }
    

    【讨论】:

    • 我会在构造函数中设置start,这使得错误地使用类变得更加困难;-)
    • 我认为不需要reset方法。不过很好的例子。
    • 好吧,理论上你应该使用System.nanoTime()而不是System.currentTimeMillis(),因为currentTimeMillis可以倒退(当系统时间改变时)。但在大多数情况下这不是一个真正的问题,因为系统时间很少改变。 nanoTime 测量经过的时间,因此不受系统时间变化的影响。
    【解决方案2】:

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

    【讨论】:

    • 最好使用System.nanoTime() 来测量经过的时间。
    • @Péter:通常情况下,差异不会很明显。我的回答是基于执行时间有点长(即多秒)的假设。
    【解决方案3】:

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

    像这样:

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

    【讨论】:

      【解决方案4】:

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

      【讨论】:

        【解决方案5】:

        如果你想了解更多关于你测量的细节,我强烈建议你使用 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

        【讨论】:

          【解决方案6】:

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

          【讨论】:

            【解决方案7】:

            Apache Commons 库有 StopWatch 类,Spring 也有 StopWatch

            【讨论】:

              【解决方案8】:

              您可以设计一个控制抽象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
              

              【讨论】:

                【解决方案9】:

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

                【讨论】:

                  猜你喜欢
                  • 2019-03-11
                  • 2021-07-03
                  • 2011-03-18
                  • 1970-01-01
                  • 2023-02-01
                  相关资源
                  最近更新 更多