Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Writing a java annotation for timing method call

I want to write a java annotation which times the method call. something like this:

@TimeIt public int someMethod() { ... } 

and when this method is invoked, it should output on console how long this method took

I know how to do it in python, this is what I want it to do:

from time import time, sleep  def time_it(func):     def wrapper(*args, **kwargs):         start = time()         func(*args, **kwargs)         stop = time()         print "The function", func.__name__, " took %.3f" % (stop - start)     wrapper.__name__ = func.__name__     return wrapper  @time_it def print_something(*args, **kwargs):     print "before sleeping"     print args, kwargs     sleep(3) # wait 3 seconds     print "after sleeping"  print_something(1, 2, 3, a="what is this?") 

So my questions are? Where do I find some documentation to write something like this, I tried apt documentation, had no luck with it. can someone help with writing something like this?

like image 666
roopesh Avatar asked Apr 21 '11 05:04

roopesh


People also ask

What is @timed annotation in java?

An annotation for marking a method, constructor, or class as timed. The metric will be registered in the application MetricRegistry. Given a method annotated with @Timed like this: @Timed(name = "fancyName") public String fancyName(String name) { return "Sir Captain " + name; }

What is @interface annotation in java?

@interface is used to create your own (custom) Java annotations. Annotations are defined in their own file, just like a Java class or interface. Here is custom Java annotation example: @interface MyAnnotation { String value(); String name(); int age(); String[] newNames(); }


1 Answers

AFAIK, Tomasz is right in saying that this can't be done using annotations. I think the confusion stems from the fact that Python decorators and Java annotations share the same syntax but are completely different in terms of the behavior they offer!

Annotations are metadata attached to your class/methods/fields. This blog post addresses the point of timing methods using AOP. Though it uses Spring, the basic premise remains the same. If you are good to go with an AOP compiler, it shouldn't be too difficult to translate the code. Another reference (spring specific) here.

EDIT: If your aim is to have a overall method timing for your application without using full blown profilers, you can use hprof for collecting total execution statistics.

like image 162
Sanjay T. Sharma Avatar answered Oct 08 '22 18:10

Sanjay T. Sharma