Tuesday, 3 November 2015

How to find out time taken by a method for execution without using any profiling tool


In order to check the performance of any method,we can read the system time just before the method is invoked and immediately after method returns.Then we can take the time difference, which will give us the time taken by a method for execution.

For example:-

                long start = System.currentTimeMillis();
                method();
                long end = System.currentTimeMillis();

System.out.println("Time taken for execution is :" + (end - start));

Sample Program:-


 /**  
  * @author Dixit  
  *   
  */  
 public class ArmstrongProgram {  
      /**  
       * @param args  
       */  
      public static void main(String[] args) {  
           long start = System.currentTimeMillis();  
           checkArmsStrongNumber();  
           long end = System.currentTimeMillis();  
           System.out.println("Time taken for execution is :" + (end - start)  
                     + " milliseconds");  
      }  
      private static void checkArmsStrongNumber() {  
           int num = 153;  
           int n = num;  
           int check = 0, remainder;  
           while (num > 0) {  
                remainder = num % 10;  
                check = check + (int) Math.pow(remainder, 3);  
                num = num / 10;  
           }  
           if (check == n)  
                System.out.println(n + " is an Armstrong Number");  
           else  
                System.out.println(n + " is not a Armstrong Number");  
      }  
 }  


Output  
 153 is an Armstrong Number  
 Time taken for execution is :1 milliseconds  


Enjoy Reading.

No comments:

Post a Comment