Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I wrap this as a helper function?

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

like image 845
Lubor Avatar asked Apr 05 '18 21:04

Lubor


1 Answers

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?

like image 95
Jacob G. Avatar answered Oct 10 '22 04:10

Jacob G.