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

前端 未结 30 2685
北荒
北荒 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 12:01

    We are using AspectJ and Java annotations for this purpose. If we need to know to execution time for a method, we simple annotate it. A more advanced version could use an own log level that can enabled and disabled at runtime.

    public @interface Trace {
      boolean showParameters();
    }
    
    @Aspect
    public class TraceAspect {
      [...]
      @Around("tracePointcut() && @annotation(trace) && !within(TraceAspect)")
      public Object traceAdvice ( ProceedingJintPoint jP, Trace trace ) {
    
        Object result;
        // initilize timer
    
        try { 
          result = jp.procced();
        } finally { 
          // calculate execution time 
        }
    
        return result;
      }
      [...]
    }
    
    0 讨论(0)
  • 2020-11-21 12:02

    I modified the code from correct answer to get result in seconds:

    long startTime = System.nanoTime();
    
    methodCode ...
    
    long endTime = System.nanoTime();
    double duration = (double)(endTime - startTime) / (Math.pow(10, 9));
    Log.v(TAG, "MethodName time (s) = " + duration);
    
    0 讨论(0)
  • 2020-11-21 12:03

    You can use Perf4j. Very cool utility. Usage is simple

    String watchTag = "target.SomeMethod";
    StopWatch stopWatch = new LoggingStopWatch(watchTag);
    Result result = null; // Result is a type of a return value of a method
    try {
        result = target.SomeMethod();
        stopWatch.stop(watchTag + ".success");
    } catch (Exception e) {
        stopWatch.stop(watchTag + ".fail", "Exception was " + e);
        throw e; 
    }
    

    More information can be found in Developer Guide

    Edit: Project seems dead

    0 讨论(0)
  • 2020-11-21 12:03

    You can try this way if just want know the time.

    long startTime = System.currentTimeMillis();
    //@ Method call
    System.out.println("Total time [ms]: " + (System.currentTimeMillis() - startTime));    
    
    0 讨论(0)
  • 2020-11-21 12:05

    Spring provides a utility class org.springframework.util.StopWatch, as per JavaDoc:

    Simple stop watch, allowing for timing of a number of tasks, exposing total running time and running time for each named task.

    Usage:

    StopWatch stopWatch = new StopWatch("Performance Test Result");
    
    stopWatch.start("Method 1");
    doSomething1();//method to test
    stopWatch.stop();
    
    stopWatch.start("Method 2");
    doSomething2();//method to test
    stopWatch.stop();
    
    System.out.println(stopWatch.prettyPrint());
    

    Output:

    StopWatch 'Performance Test Result': running time (millis) = 12829
    -----------------------------------------
    ms     %     Task name
    -----------------------------------------
    11907  036%  Method 1
    00922  064%  Method 2
    

    With Aspects:

    @Around("execution(* my.package..*.*(..))")
    public Object logTime(ProceedingJoinPoint joinPoint) throws Throwable {
        StopWatch stopWatch = new StopWatch();
        stopWatch.start();
        Object retVal = joinPoint.proceed();
        stopWatch.stop();
        log.info(" execution time: " + stopWatch.getTotalTimeMillis() + " ms");
        return retVal;
    }
    
    0 讨论(0)
  • 2020-11-21 12:06

    There is always the old-fashioned way:

    long startTime = System.nanoTime();
    methodToTime();
    long endTime = System.nanoTime();
    
    long duration = (endTime - startTime);  //divide by 1000000 to get milliseconds.
    
    0 讨论(0)
提交回复
热议问题