Java Reference
In-Depth Information
Returning to the numbers-summing exercise, we said that you can expect a significant
performance improvement in its parallel version when running it on a multicore processor. You
now have three methods executing exactly the same operation in three different ways (iterative
style, sequential reduction, and parallel reduction), so let's see which is the fastest one!
7.1.2. Measuring stream performance
We claimed that the parallelized summing method should perform better than the sequential
and the iterative methods. Nevertheless, in software engineering guessing is never a good idea!
Especially when optimizing performance you should always follow three golden rules: measure,
measure, measure. To this purpose you can develop a method very similar to the basic harness
you used in section 6.6.2 to compare the performances of the two collectors partitioning
numbers into prime and nonprime, as shown in the following listing.
Listing 7.1. Measuring performance of a function summing the first n
numbers
public long measureSumPerf(Function<Long, Long> adder, long n) {
long fastest = Long.MAX_VALUE;
for (int i = 0; i < 10; i++) {
long start = System.nanoTime();
long sum = adder.apply(n);
long duration = (System.nanoTime() - start) / 1_000_000;
System.out.println("Result: " + sum);
if (duration < fastest) fastest = duration;
}
return fastest;
}
Here this method takes as arguments a function and a long. It applies the function 10 times on
the long passed to the method, registers the time taken by each execution in milliseconds, and
returns the duration of the fastest one. Supposing that you group all the methods you developed
previously into a class named ParallelStreams, you can use this harness to check how long the
sequential adder function takes to sum the first 10 million natural numbers:
System.out.println("Sequential sum done in: " +
measureSumPerf(ParallelStreams::sequentialSum, 10_000_000) + " msecs");
 
Search WWH ::




Custom Search