Java Reference
In-Depth Information
71
System.out.printf(
" average: %f%n"
, stats.getAverage());
72
}
73
}
// end class StreamStatisticsComparison
Calculations performed separately
count: 10,000,000
sum: 5,003,695,285
min: 1
max: 1,000
average: 500.369529
Total time in milliseconds: 173
Calculating statistics on sequential stream
Statistics
count: 10,000,000
sum: 5,003,695,285
min: 1
max: 1,000
average: 500.369529
Total time in milliseconds: 69
Calculating statistics on parallel stream
Statistics
count: 10,000,000
sum: 5,003,695,285
min: 1
max: 1,000
average: 500.369529
Total time in milliseconds: 38
Fig. 23.29
|
Comparing performance of sequential and parallel stream operations. (Part 3 of 3.)
Performing Stream Operations with Separate Passes of a Sequential Stream
Section 17.3 demonstrated various numerical operations on
IntStream
s. Lines 20-26 per-
form and time the
count
,
sum
,
min
,
max
and
average
stream operations each performed
individually on a
LongStream
returned by
Arrays
method
stream
. Lines 29-36 then dis-
play the results and the total time required to perform all five operations.
Performing Stream Operations with a Single Pass of a Sequential Stream
Lines 39-48 demonstrate the performance improvement you get by using
LongStream
method
summaryStatistics
to determine the count, sum, minimum value, maximum
value and average in one pass of a
sequential
LongStream
—all streams are sequential by de-
fault. This operation took approximately 40% of the time required to perform the five op-
erations separately.
Performing Stream Operations with a Single Pass of a Parallel Stream
Lines 51-60 demonstrate the performance improvement you get by using
LongStream
method
summaryStatistics
on a
parallel
LongStream
. To obtain a parallel stream that can
take advantage of multi-core processors, simply invoke method
parallel
on an existing
stream. As you can see from the sample output, performing the operations on a parallel
stream decreased the total time required even further—taking approximately 55% of the