Java Reference

In-Depth Information

It's quite complex, so I'll go through how this works in a few steps. The input parameter
n
is

the size of the time window we're calculating our moving average over. At we take a copy

of our input data. Because our prefix calculation is a mutating operation, we do this to avoid

altering the original source.

In we apply the prefix operation, adding up values in the process. So now our
sums
vari-

able holds the running total of the sums so far. For example, given the input
0, 1, 2, 3,

4, 3.5
, it would hold
0.0, 1.0, 3.0, 6.0, 10.0, 13.5
.

Now that we have the complete running totals, we can find the sum over the time window by

subtracting the running total at the beginning of the time window. The average is this divided

by
n
. We can do this calculation using the existing streams library, so let's use it! We kick off

the stream in by using
Intstream.range
to get a stream ranging over the indices of the

values we want.

At we subtract away the running total at the start and then do the division in order to get

the average. It's worth noting that there's an edge case for the running total at element n - 1,

where there is no running total to subtract to begin with. Finally, at , we convert the
Stream

back to an array.

Key Points

▪ Data parallelism is a way to split up work to be done on many cores at the same time.

▪ If we use the streams framework to write our code, we can utilize data parallelism by

calling the
parallel
or
parallelStream
methods.

▪ The five main factors influencing performance are the data size, the source data struc-

ture, whether the values are packed, the number of available cores, and how much pro-

cessing time is spent on each element.

Exercises

Make it run in parallel using streams.

Example 6-10. Sequentially summing the squares of numbers in a list