42 lines
1.2 KiB
Java
Raw Normal View History

2016-11-23 09:05:26 -08:00
// concurrent/Summing3.java
2016-12-30 17:23:13 -08:00
// (c)2017 MindView LLC: see Copyright.txt
2016-07-05 14:46:09 -06:00
// We make no guarantees that this code is fit for any purpose.
2016-09-23 13:23:35 -06:00
// Visit http://OnJava8.com for more book information.
2016-07-05 14:46:09 -06:00
import java.util.*;
public class Summing3 {
static long basicSum(Long[] ia) {
long sum = 0;
int size = ia.length;
for(int i = 0; i < size; i++)
2016-07-05 14:46:09 -06:00
sum += ia[i];
return sum;
}
// Approximate largest value of SZ before
// running out of memory on my machine:
public static final int SZ = 10_000_000;
2016-07-05 14:46:09 -06:00
public static final long CHECK =
(long)SZ * ((long)SZ + 1)/2;
public static void main(String[] args) {
System.out.println(CHECK);
Long[] aL = new Long[SZ+1];
Arrays.parallelSetAll(aL, i -> (long)i);
2016-07-05 14:46:09 -06:00
Summing.timeTest("Long Array Stream Reduce",
CHECK, () ->
Arrays.stream(aL).reduce(0L, Long::sum));
2016-07-05 14:46:09 -06:00
Summing.timeTest("Long Basic Sum", CHECK, () ->
basicSum(aL));
2016-07-05 14:46:09 -06:00
// Destructive summation:
Summing.timeTest("Long parallelPrefix",CHECK, ()-> {
Arrays.parallelPrefix(aL, Long::sum);
return aL[aL.length - 1];
2016-07-05 14:46:09 -06:00
});
}
}
/* Output:
50000005000000
2016-07-27 11:12:11 -06:00
Long Array Stream Reduce: 1038ms
2016-07-05 14:46:09 -06:00
Long Basic Sum: 21ms
2016-07-27 11:12:11 -06:00
Long parallelPrefix: 3616ms
2016-07-05 14:46:09 -06:00
*/