示例 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()
的递归方法的执行时间。
另请阅读