How do I get a method's execution time? Is there a Timer utility class for things like timing how long a task takes, etc?
Most of the searches on Google return results for timers that schedule threads and tasks, which is not what I want.
How do I get a method's execution time? Is there a Timer utility class for things like timing how long a task takes, etc?
Most of the searches on Google return results for timers that schedule threads and tasks, which is not what I want.
Ok, this is a simple class to be used for simple simple timing of your functions. There is an example below it.
Sample of use:
Sample of console output:
There are a couple of ways to do that. I normally fall back to just using something like this:
or the same thing with System.nanoTime();
For something more on the benchmarking side of things there seems also to be this one: http://jetm.void.fm/ Never tried it though.
Spring provides a utility class org.springframework.util.StopWatch, as per JavaDoc:
Usage:
Output:
With Aspects:
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.
Using AOP/AspectJ and
@Loggable
annotation from jcabi-aspects you can do it easy and compact:Every call to this method will be sent to SLF4J logging facility with
DEBUG
logging level. And every log message will include execution time.