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

前端 未结 30 2770
北荒
北荒 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:59

    System.currentTimeMillis(); IS NOT a good approach for measuring the performance of your algorithms. It measures the total time you experience as a user watching the computer screen. It includes also time consumed by everything else running on your computer in the background. This could make a huge difference in case you have a lot of programs running on your workstation.

    Proper approach is using java.lang.management package.

    From http://nadeausoftware.com/articles/2008/03/java_tip_how_get_cpu_and_user_time_benchmarking website (archive link):

    • "User time" is the time spent running your application's own code.
    • "System time" is the time spent running OS code on behalf of your application (such as for I/O).

    getCpuTime() method gives you sum of those:

    import java.lang.management.ManagementFactory;
    import java.lang.management.ThreadMXBean;
    
    public class CPUUtils {
    
        /** Get CPU time in nanoseconds. */
        public static long getCpuTime( ) {
            ThreadMXBean bean = ManagementFactory.getThreadMXBean( );
            return bean.isCurrentThreadCpuTimeSupported( ) ?
                bean.getCurrentThreadCpuTime( ) : 0L;
        }
    
        /** Get user time in nanoseconds. */
        public static long getUserTime( ) {
            ThreadMXBean bean = ManagementFactory.getThreadMXBean( );
            return bean.isCurrentThreadCpuTimeSupported( ) ?
                bean.getCurrentThreadUserTime( ) : 0L;
        }
    
        /** Get system time in nanoseconds. */
        public static long getSystemTime( ) {
            ThreadMXBean bean = ManagementFactory.getThreadMXBean( );
            return bean.isCurrentThreadCpuTimeSupported( ) ?
                (bean.getCurrentThreadCpuTime( ) - bean.getCurrentThreadUserTime( )) : 0L;
        }
    
    }
    

提交回复
热议问题