Assume I am having such code snippets:
try {
// code I need to wrap to be a helper
long t0 = System.nanoTime();
obj.doSomething(); // a void function
long t1 = System.nanoTime();
Logger.info("doSomthing takes {} nanoseconds", t1-t0);
} catch (IOException ex) {
Logger.error("something wrong happened");
}
// another code
try {
long t0 = System.nanoTime();
obj.doAnotherThing(); // void function
long t1 = System.nanoTime();
Logger.info("doSomthing takes {} nanoseconds", t1-t0);
} catch (IOException ex) {
Logger.error("something wrong happened");
}
So my question is actually how I can pass that void function as a parameter to a helper function, so that I can avoid redundant code for measuring the execution time of the function.
Follow Up: what if doSomething can throw IOException
In this case how should I invoke the function in the lambda world if I don't want to catch the exception in labmda.
Thanks
You can use a Runnable
:
public void timeThis(Runnable runnable) {
long t0 = System.nanoTime();
runnable.run();
long t1 = System.nanoTime();
Logger.info("Execution took {} nanoseconds", t1 - t0);
}
You can then pass the function you want to run as an argument to timeThis
:
timeThis(() -> obj.doSomething());
If obj.doSomething()
happens to throw an IOException
like you mentioned below, you can simply catch it within the body of the Runnable
:
timeThis(() -> {
try {
obj.doSomething();
} catch (IOException e) {
e.printStackTrace();
}
});
Note: This is not a proper benchmark. See: How do I write a correct micro-benchmark in Java?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With