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