3

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?

kxirog
  • 392
  • 1
  • 2
  • 9
  • 2
    As a side-note, if you intend to have this to do micro benchmarks then you'd be better off learning a benchmarking framework like JMH. – Tunaki Jan 31 '16 at 11:07
  • 2
    I really hope you're not planning to use this for benchmarking. – Brian Goetz Jan 31 '16 at 18:15
  • @BrianGoetz Yes I do intend to use this for benchmarking. Could you explain what the problem with that would be?... – kxirog Feb 01 '16 at 03:59
  • 1
    [How do I write a correct micro-benchmark in Java?](http://stackoverflow.com/a/513259/2711488) – Holger Feb 01 '16 at 10:40

1 Answers1

6

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

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

long elapsed = time( () -> myMethod(foo, bar));
dkatzel
  • 31,188
  • 3
  • 63
  • 67