0

When profiling execution time of java code, the common approach is to utilise the following approach:

long start = System.nanoTime();
expensiveMeothd(array);
long runtime = System.nanoTime() - start;

Unfortunately this approach is not applicable in the confines of Java8 stream syntax.

What is the best practice for measuring a stream method execution time? For example if I wanted to calculate how long: .map(x -> someexpensiveMeothod(x)) takes to execute.

One approach I have considered is wrapping the stream return in an object that stores the nanotime. However this approach seems less than ideal. Here is my concept:

public class Profiler {
    public List list;
    public long startTime;
    public long endTime;

    public Profiler(List list, long s, long e) {
        this.list = list;
        this.startTime = s;
        this.endTime = e;
    }
}

List<Profiler> results = myList.stream()
               .map(x -> new Profiler(x, System.nanoTime(), null))
               .map(x -> {
                    expensiveMethod(x.list);
                    x.endTime = System.nanoTime(); 
                    return x;  
               })
               .collect(Collectors.toList());

Additionally, is it actually appropriate to measure the execution time of individual stream method calls on principle?

Jack Dalton
  • 3,536
  • 5
  • 23
  • 40
  • Your code doesn't compile, and if it did, it wouldn't run because there's no terminal operation on the stream. Benchmarking streams will not give you correct results for your method(s) anyway, as there's added stream overhead. – Jacob G. Apr 11 '18 at 00:31
  • 2
    If the goal is to benchmark expensiveMethod, why not setup a specific testbed outside of the streaming code? Doing it inside the stream is incredibly awkward, and probably noisy due to internal stream logic – Krease Apr 11 '18 at 01:17
  • Yeah I thought as much, just wanted to know if it was possible (in a clean and un-noisy way). Thanks. @JacobG. Sorry I should have specified that the code was conceptual and not syntactically/logically correct, i'll edit the initial post to reflect your comment. – Jack Dalton Apr 11 '18 at 10:50

0 Answers0