How do I time a method's execution in Java?

前端 未结 30 2700
北荒
北荒 2020-11-21 11:15
  1. How do I get a method\'s execution time?
  2. Is there a Timer utility class for things like timing how long a task takes, etc?

Mos

30条回答
  •  陌清茗
    陌清茗 (楼主)
    2020-11-21 11:57

    I have written a method to print the method execution time in a much readable form. For example, to calculate the factorial of 1 Million, it takes approximately 9 minutes. So the execution time get printed as:

    Execution Time: 9 Minutes, 36 Seconds, 237 MicroSeconds, 806193 NanoSeconds
    

    The code is here:

    public class series
    {
        public static void main(String[] args)
        {
            long startTime = System.nanoTime();
    
            long n = 10_00_000;
            printFactorial(n);
    
            long endTime = System.nanoTime();
            printExecutionTime(startTime, endTime);
    
        }
    
        public static void printExecutionTime(long startTime, long endTime)
        {
            long time_ns = endTime - startTime;
            long time_ms = TimeUnit.NANOSECONDS.toMillis(time_ns);
            long time_sec = TimeUnit.NANOSECONDS.toSeconds(time_ns);
            long time_min = TimeUnit.NANOSECONDS.toMinutes(time_ns);
            long time_hour = TimeUnit.NANOSECONDS.toHours(time_ns);
    
            System.out.print("\nExecution Time: ");
            if(time_hour > 0)
                System.out.print(time_hour + " Hours, ");
            if(time_min > 0)
                System.out.print(time_min % 60 + " Minutes, ");
            if(time_sec > 0)
                System.out.print(time_sec % 60 + " Seconds, ");
            if(time_ms > 0)
                System.out.print(time_ms % 1E+3 + " MicroSeconds, ");
            if(time_ns > 0)
                System.out.print(time_ns % 1E+6 + " NanoSeconds");
        }
    }
    

提交回复
热议问题