2016-11-23 09:05:26 -08:00
|
|
|
// concurrent/Summing.java
|
2020-10-07 13:35:40 -06:00
|
|
|
// (c)2020 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.stream.*;
|
|
|
|
import java.util.function.*;
|
2016-12-17 10:51:25 -08:00
|
|
|
import onjava.Timer;
|
2016-07-05 14:46:09 -06:00
|
|
|
|
|
|
|
public class Summing {
|
|
|
|
static void timeTest(String id, long checkValue,
|
|
|
|
LongSupplier operation) {
|
|
|
|
System.out.print(id + ": ");
|
2016-12-17 10:51:25 -08:00
|
|
|
Timer timer = new Timer();
|
2017-01-02 14:20:31 -08:00
|
|
|
long result = operation.getAsLong();
|
2016-07-05 14:46:09 -06:00
|
|
|
if(result == checkValue)
|
2016-12-17 10:51:25 -08:00
|
|
|
System.out.println(timer.duration() + "ms");
|
2016-07-05 14:46:09 -06:00
|
|
|
else
|
2016-11-21 12:37:57 -08:00
|
|
|
System.out.format("result: %d%ncheckValue: %d%n",
|
2016-07-05 14:46:09 -06:00
|
|
|
result, checkValue);
|
|
|
|
}
|
2016-11-21 12:37:57 -08:00
|
|
|
public static final int SZ = 100_000_000;
|
2016-07-05 14:46:09 -06:00
|
|
|
// This even works:
|
2016-11-21 12:37:57 -08:00
|
|
|
// public static final int SZ = 1_000_000_000;
|
2016-07-05 14:46:09 -06:00
|
|
|
public static final long CHECK =
|
2016-12-04 09:30:08 -08:00
|
|
|
(long)SZ * ((long)SZ + 1)/2; // Gauss's formula
|
2016-07-05 14:46:09 -06:00
|
|
|
public static void main(String[] args) {
|
|
|
|
System.out.println(CHECK);
|
|
|
|
timeTest("Sum Stream", CHECK, () ->
|
|
|
|
LongStream.rangeClosed(0, SZ).sum());
|
|
|
|
timeTest("Sum Stream Parallel", CHECK, () ->
|
|
|
|
LongStream.rangeClosed(0, SZ).parallel().sum());
|
|
|
|
timeTest("Sum Iterated", CHECK, () ->
|
|
|
|
LongStream.iterate(0, i -> i + 1)
|
|
|
|
.limit(SZ+1).sum());
|
2016-12-31 14:57:31 -08:00
|
|
|
// Slower & runs out of memory above 1_000_000:
|
2016-07-05 14:46:09 -06:00
|
|
|
// timeTest("Sum Iterated Parallel", CHECK, () ->
|
|
|
|
// LongStream.iterate(0, i -> i + 1)
|
|
|
|
// .parallel()
|
|
|
|
// .limit(SZ+1).sum());
|
|
|
|
}
|
|
|
|
}
|
|
|
|
/* Output:
|
|
|
|
5000000050000000
|
2017-05-10 11:45:39 -06:00
|
|
|
Sum Stream: 167ms
|
|
|
|
Sum Stream Parallel: 46ms
|
|
|
|
Sum Iterated: 284ms
|
2016-07-05 14:46:09 -06:00
|
|
|
*/
|