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

前端 未结 30 2748
北荒
北荒 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;
      }
      [...]
    }
    

提交回复
热议问题