如何获得方法的执行时间? 是否有Timer实用程序类来计时任务所需的时间等?

在谷歌上的大多数搜索都返回调度线程和任务的计时器的结果,这不是我想要的。


当前回答

可以使用javaagent修改java类字节,动态添加监控代码。github上有一些开源工具可以帮你做到这一点。 如果您想自己完成,只需实现javaagent,使用javassist修改要监视的方法,并在方法返回之前修改监视代码。它很干净,你甚至可以监视没有源代码的系统。

其他回答

如果你只是想知道时间,可以试试这种方法。

long startTime = System.currentTimeMillis();
//@ Method call
System.out.println("Total time [ms]: " + (System.currentTimeMillis() - startTime));    

在java ee中对我有效的策略是:

Create a class with a method annotated with @AroundInvoke; @Singleton public class TimedInterceptor implements Serializable { @AroundInvoke public Object logMethod(InvocationContext ic) throws Exception { Date start = new Date(); Object result = ic.proceed(); Date end = new Date(); System.out.println("time: " + (end.getTime - start.getTime())); return result; } } Annotate the method that you want to monitoring: @Interceptors(TimedInterceptor.class) public void onMessage(final Message message) { ...

我希望这能有所帮助。

new Timer(""){{
    // code to time 
}}.timeMe();



public class Timer {

    private final String timerName;
    private long started;

    public Timer(String timerName) {
        this.timerName = timerName;
        this.started = System.currentTimeMillis();
    }

    public void timeMe() {
        System.out.println(
        String.format("Execution of '%s' takes %dms.", 
                timerName, 
                started-System.currentTimeMillis()));
    }

}

为此,我们使用了AspectJ和Java注释。如果我们需要知道一个方法的执行时间,我们可以简单地注释它。更高级的版本可以使用自己的日志级别,可以在运行时启用和禁用。

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;
  }
  [...]
}

这可能不是您想让我说的,但是这是AOP的一个很好的用法。在您的方法周围使用代理拦截器,并在其中进行计时。

遗憾的是,AOP的什么、为什么和如何超出了这个答案的范围,但这就是我可能会做的事情。

编辑:如果你有兴趣的话,这里有一个Spring AOP的链接可以帮助你入门。这是Iive在java中遇到的最容易访问的AOP实现。

另外,考虑到其他人的简单建议,我应该补充一点:AOP适用于不希望时间之类的东西侵入代码的情况。但在很多情况下,这种简单易行的方法是可以的。