48 lines
1.5 KiB
Java
Raw Normal View History

2016-11-23 09:05:26 -08:00
// concurrent/Summing.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.stream.*;
import java.util.function.*;
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 + ": ");
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)
System.out.println(timer.duration() + "ms");
2016-07-05 14:46:09 -06:00
else
System.out.format("result: %d%ncheckValue: %d%n",
2016-07-05 14:46:09 -06:00
result, checkValue);
}
public static final int SZ = 100_000_000;
2016-07-05 14:46:09 -06:00
// This even works:
// public static final int SZ = 1_000_000_000;
2016-07-05 14:46:09 -06:00
public static final long CHECK =
(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
Sum Stream: 167ms
Sum Stream Parallel: 46ms
Sum Iterated: 284ms
2016-07-05 14:46:09 -06:00
*/