如何测量 Java 方法的执行时间?

javaserver side programmingprogramming

一般来说,经过的时间是从事件的起点到终点的时间。以下是在 Java 中查找经过时间的各种方法 -

  • currentTimeMillis() 方法以毫秒为单位返回当前时间。要查找方法的经过时间,您可以获取所需方法执行前后的时间值之间的差值。
  • nanoTime() 方法以纳秒为单位返回当前时间。要查找某个方法的已用时间,您可以获取所需方法执行前后的时间值差。
  • Instant 类的 now() 方法返回当前时间,而 Duration.between() 方法返回给定两个时间值之间的差,以获取已用时间,检索所需方法执行前后的时间值,并使用 Duration.between() 方法检索持续时间。
  • Apache commons 库提供了一个名为 Stopwatch 的类,它提供了 start()stop()getTime() 方法来查找方法执行所花费的时间。

示例

以下示例演示如何使用上述方法查找方法的执行时间 −

import java.time.Duration;
import java.time.Instant;
import org.apache.commons.lang3.time.StopWatch;
public class Example {
   public void test(){
      int num = 0;
      for(int i=0; i<=50; i++){  
         num =num+i;
         System.out.print(num+", ");
      }  
   }
   public static void main(String args[]){
      Example obj = new Example();
      long start1 = System.nanoTime();
      obj.test();
      long end1 = System.nanoTime();      
      System.out.println("Elapsed Time in nano seconds: "+ (end1-start1));      
      long start2 = System.currentTimeMillis();
      obj.test();
      long end2 = System.currentTimeMillis();      
      System.out.println("Elapsed Time in milli seconds: "+ (end2-start2));
      Instant inst1 = Instant.now();
      obj.test();
      Instant inst2 = Instant.now();      
      System.out.println("Elapsed Time: "+ Duration.between(inst1, inst2).toString());
      StopWatch stopWatch = new StopWatch();
      stopWatch.start();
      obj.test();
      stopWatch.stop();      
      System.out.println("Elapsed Time in minutes: "+ stopWatch.getTime());
   }
}

输出

0, 1, 3, 6, 10, 15, 21, 28, 36, 45, 55, 66, 78, 91, 105, 120, 136, 153, 171, 190, 210, 231, 253, 276, 300, 325, 351, 378, 406, 435, 465, 496, 528, 561, 595, 630, 666, 703, 741, 780, 820, 861, 903, 946, 990, 1035, 1081, 1128, 1176, 1225, 1275, Elapsed Time in nano seconds: 1882300
0, 1, 3, 6, 10, 15, 21, 28, 36, 45, 55, 66, 78, 91, 105, 120, 136, 153, 171, 190, 210, 231, 253, 276, 300, 325, 351, 378, 406, 435, 465, 496, 528, 561, 595, 630, 666, 703, 741, 780, 820, 861, 903, 946, 990, 1035, 1081, 1128, 1176, 1225, 1275, Elapsed Time in milli seconds: 1
0, 1, 3, 6, 10, 15, 21, 28, 36, 45, 55, 66, 78, 91, 105, 120, 136, 153, 171, 190, 210, 231, 253, 276, 300, 325, 351, 378, 406, 435, 465, 496, 528, 561, 595, 630, 666, 703, 741, 780, 820, 861, 903, 946, 990, 1035, 1081, 1128, 1176, 1225, 1275, Elapsed Time: PT0.001S
0, 1, 3, 6, 10, 15, 21, 28, 36, 45, 55, 66, 78, 91, 105, 120, 136, 153, 171, 190, 210, 231, 253, 276, 300, 325, 351, 378, 406, 435, 465, 496, 528, 561, 595, 630, 666, 703, 741, 780, 820, 861, 903, 946, 990, 1035, 1081, 1128, 1176, 1225, 1275, Elapsed Time in minutes: 1

相关文章