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

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

    As "skaffman" said, use AOP OR you can use run time bytecode weaving, just like unit test method coverage tools use to transparently add timing info to methods invoked.

    You can look at code used by open source tools tools like Emma (http://downloads.sourceforge.net/emma/emma-2.0.5312-src.zip?modtime=1118607545&big_mirror=0). The other opensource coverage tool is http://prdownloads.sourceforge.net/cobertura/cobertura-1.9-src.zip?download.

    If you eventually manage to do what you set out for, pls. share it back with the community here with your ant task/jars.

    0 讨论(0)
  • 2020-11-21 11:57

    I basically do variations of this, but considering how hotspot compilation works, if you want to get accurate results you need to throw out the first few measurements and make sure you are using the method in a real world (read application specific) application.

    If the JIT decides to compile it your numbers will vary heavily. so just be aware

    0 讨论(0)
  • 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");
        }
    }
    
    0 讨论(0)
  • 2020-11-21 11:57
    long startTime = System.currentTimeMillis();
    // code goes here
    long finishTime = System.currentTimeMillis();
    long elapsedTime = finishTime - startTime; // elapsed time in milliseconds
    
    0 讨论(0)
  • 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;
        }
    
    }
    
    0 讨论(0)
  • 2020-11-21 12:00

    Using AOP/AspectJ and @Loggable annotation from jcabi-aspects you can do it easy and compact:

    @Loggable(Loggable.DEBUG)
    public String getSomeResult() {
      // return some value
    }
    

    Every call to this method will be sent to SLF4J logging facility with DEBUG logging level. And every log message will include execution time.

    0 讨论(0)
提交回复
热议问题