Shehan Perera
Shehan Perera

Reputation: 349

Using Java agent and byte-buddy for measure execution time

I am trying to create a java agent for measure execution time of a method using byte buddy lib without changing main method . I follow the tutorials and create following codes. When executing this MonitorInspector must give time that spend for execution. But it not working only giving the output of as follows.

Premain

Main Class

Is any way i can fix this. please help me to slow this problem.

This is my codes.. AgentTest( This code of agent)

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));
    }}}

Main Class

public class SampleClass {

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


}}

Upvotes: 2

Views: 1300

Answers (3)

EdisonX
EdisonX

Reputation: 1

I see type(ElementMatchers.nameEndsWith("Timed")) in ur code, probably its the reason 4 the behavior of ur code

Upvotes: 0

Rafael Winterhalter
Rafael Winterhalter

Reputation: 44042

You can also achieve this by using Advice which uses code inlining and should result in better runtime performance:

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));
  }
}

and apply the advice by

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

This way, the timing does not show up in stacktraces either.

Upvotes: 5

Shehan Perera
Shehan Perera

Reputation: 349

I found good solution for this given by Rafael Winterhalter.Go to following Link [ https://github.com/raphw/byte-buddy/issues/257 ]

Upvotes: 2

Related Questions