Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Writing a generalized method to time any other method using Java 8 lambdas

I've been trying to figure out if there's a way to write a method that takes a Java 8 method reference as an input,runs that method and returns the time it took to run.

public static long time(Runnable c) {
    long start, end;
    start = System.currentTimeMillis();
    c.run();
    end = System.currentTimeMillis();
    return (end - start);
}

This is what I have so far, but this will only work for a method with no parameters...I'm looking for something that can work with a method that can take parameters as well. Is that possible?

like image 779
kxirog Avatar asked Aug 06 '26 10:08

kxirog


1 Answers

Well, a work around is to wrap your method inside a lambda

int foo =...
Object bar = ...

long elapsed = time( () -> myMethod(foo, bar));
like image 88
dkatzel Avatar answered Aug 08 '26 07:08

dkatzel



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!