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.
Come on guys! Nobody mentioned the Guava way to do that (which is arguably awesome):
The nice thing is that Stopwatch.toString() does a good job of selecting time units for the measurement. I.e. if the value is small, it'll output 38 ns, if it's long, it'll show 5m 3s
Even nicer:
Note: Google Guava requires Java 1.6+
Really good code.
http://www.rgagnon.com/javadetails/java-0585.html
I basically do variations of this, but considering how hotspot compilation works, if you want to get accurate results you need to throw out the first few measurements and make sure you are using the method in a real world (read application specific) application.
If the JIT decides to compile it your numbers will vary heavily. so just be aware
You can use Metrics library which provides various measuring instruments. Add dependency:
And configure it for your environment.
Methods can be annotated with @Timed:
or piece of code wrapped with Timer:
Aggregated metrics can exported to console, JMX, CSV or other.
@Timed
metrics output example:I go with the simple answer. Works for me.
It works quite well. The resolution is obviously only to the millisecond, you can do better with System.nanoTime(). There are some limitations to both (operating system schedule slices, etc.) but this works pretty well.
Average across a couple of runs (the more the better) and you'll get a decent idea.
JEP 230: Microbenchmark Suite
FYI, JEP 230: Microbenchmark Suite is an OpenJDK proposal to:
This proposal did not make the cut for Java 9 but may be added later.
Java Microbenchmark Harness (JMH)
In the meantime you may want to look at the Java Microbenchmark Harness (JMH) project on which the proposal is based.