I am trying to measure the execution time for several methods. so I was thinking to make a method instead of duplicate same code many times.
Here is my code:
private void MeasureExecutionTime(Method m)
{
startTime = System.nanoTime();
try
{
m();
}
finally
{
endTime = System.nanoTime();
}
elapsedTime = endTime - startTime;
System.out.println("This takes " + elapsedTime + " ns.");
}
Suppose I have myMethod()
, how can I use MeasureExecutionTime()
to measure myMethod
's execution time?
the simplest way to do this is to pass an interface. So something like
and then in you can have methods that take CommonFuncs as an argument. The implementations of those methods can call the
execute
method.I have a object call Counter which basically looks like this:
With two "time" methods for timing methods that return something and other methods which are void.
I chose to rethrow the exceptions as runtime exceptions (as i'm not a fan of checked exceptions) but you could just as well make your custom MyRunnable interface throw exceptions and just catch and re-throw them. Here's a usage of the above:
Or this, in the returning-value case:
I like this because my counter objects can be exposed over JMX and injected wherever i need them. You could do what you've asked with reflection, but i think that would be messy (IMHO).
You are in the correct path, you need to pass the Method object, the target object on which to execute the method and the arguments it takes and then invoke it into your try catch, something like:
you may do smth like:
Methods aren't first-class objects in Java, so they can't be passed as parameters. You could use wrap your method call in an annoymous class that extends e.g. the
Runnable
interface:I agree with @hvgotcodes, But yes, it is possible, though you don't call it like
m()
, but using invoke (which means that you probably should pass another argument or two with it...).