Java教程

Java 计算方法执行时间的程序

计算方法执行时间的Java程序

在这个例子中,我们将学习计算Java中普通方法和递归方法的执行时间。
要理解此示例,您应该了解以下Java 编程主题:
Java 方法 Java 递归

示例1: Java程序计算方法执行时间

class Main {
  // create a method
  public void display() {
    System.out.println("Calculating Method execution time:");
  }
  // main method
  public static void main(String[] args) {
    // create an object of the Main class
    Main obj = new Main();
    // get the start time
    long start = System.nanoTime();
    // call the method
    obj.display();
    // get the end time
    long end = System.nanoTime();
    // execution time
    long execution = end-start;
    System.out.println("Execution time: " + execution + " nanoseconds");
  }
}
输出
Calculating Method execution time:
Execution time: 656100 nanoseconds
在上面的例子中,我们创建了一个名为 display() 的方法。该方法将一条语句打印到控制台。程序计算 display()方法的执行时间。
这里,我们使用了 System 类的方法 nanoTime()nanoTime() 方法以纳秒为单位返回正在运行的 JVM 的当前值。

例2: 计算Recursive方法的执行时间

class Main {
  // create a recursive method
  public int factorial( int n ) {
    if (n != 0)  // termination condition
        return n * factorial(n-1); // recursive call
    else
        return 1;
}
  // main method
  public static void main(String[] args) {
    // create object of Main class
    Main obj = new Main();
    // get the start time
    long start = System.nanoTime();
    // call the method
    obj.factorial(128);
    // get the end time
    long end = System.nanoTime();
    // execution time in seconds
    long execution = (end-start);
    System.out.println("Execution time of Recursive Method is");
    System.out.println(execution + " nanoseconds");
  }
}
输出
Execution time of Recursive Method is
18600 nanoseconds
在上面的例子中,我们正在计算名为 factorial()的递归方法的执行时间。
昵称: 邮箱:
Copyright © 2022 立地货 All Rights Reserved.
备案号:京ICP备14037608号-4