使用Java代理和byte-buddy来测量执行时间

问题描述 投票:1回答:2

我正在尝试使用byte buddy lib为方法的度量执行时间创建一个java代理,而不更改main方法。我按照教程并创建以下代码。执行此MonitorInspector时,必须给出执行时间。但它的工作效果不如下。

倍美力

主类

我有什么方法可以解决这个问题。请帮我减缓这个问题。

这是我的代码.. AgentTest(此代理代码)

class AgentTest {

public static void premain(String arguments, Instrumentation ins) {
    System.out.println("Premain");
    new AgentBuilder.Default()
            .type(ElementMatchers.nameEndsWith("Timed"))
            .transform((builder, type, classLoader, module)->builder.method(ElementMatchers.any()).intercept(MethodDelegation.to(MonitorInterceptor.class))
            ).installOn(ins);
}}

MonitorInspector

class MonitorInterceptor {
@RuntimeType
public static Object intercept(@Origin Method method,@SuperCall Callable<?> callable) throws Exception {
    long start = System.currentTimeMillis();
    try {
        return callable.call();
    } finally {  System.out.println(method + " took " +(System.currentTimeMillis()-start));
    }}}

主类

public class SampleClass {

public static void main(String[] args) {
    System.out.println("Main Class");
    Methods.test(0);


}}
java performance agent byte-buddy
2个回答
2
投票

您也可以通过使用代码内联的Advice来实现这一点,并且应该可以带来更好的运行时性能:

class TimerAdvice {
  @Advice.OnMethodEnter
  static long enter() {
    return System.currentTimeMillis();
  }
  @Advice.OnMethodExit(onException = Throwable.class)
  static void exit(@Advice.Origin String method, @Advice.Enter long start) {
    System.out.println(method + " took " + (System.currentTimeMillis() - start));
  }
}

并通过提出建议

new AgentBuilder.Default()
  .type(ElementMatchers.nameEndsWith("Timed"))
  .transform((builder, type, classLoader, module) -> 
      builder.visit(Advice.to(TimerAdvice).on(ElementMatchers.any()));
  );

这样,时间也不会出现在堆栈跟踪中。


0
投票

我找到了很好的解决方案,由Rafael Winterhalter给出。转到以下链接[https://github.com/raphw/byte-buddy/issues/257]

© www.soinside.com 2019 - 2024. All rights reserved.