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:计算递归方法执行时间

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()的递归方法的执行时间。


另请阅读

你觉得这篇文章有帮助吗?

我们的高级学习平台,凭借十多年的经验和数千条反馈创建。

以前所未有的方式学习和提高您的编程技能。

试用 Programiz PRO
  • 交互式课程
  • 证书
  • AI 帮助
  • 2000+ 挑战