Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /**
- * simulates throwing two dice
- * @return the sum of the two die
- */
- private static int twoDiceThrows() {
- final int dieA = ThreadLocalRandom.current().nextInt(5) + 1;
- final int dieB = ThreadLocalRandom.current().nextInt(5) + 1;
- return dieA + dieB;
- }
- private static Map<Integer, Double> serialDiceRolls(long N) {
- double fraction = 1.0 / N;
- return LongStream.range(0, N)
- .mapToObj((i) -> twoDiceThrows())
- .collect(groupingBy(side -> side,
- summingDouble(n -> fraction)));
- }
- private static Map<Integer, Double> parallelDiceRolls(long N) {
- double fraction = 1.0 / N;
- return LongStream.range(0, N)
- .parallel() // *
- .mapToObj((i) -> twoDiceThrows())
- .collect(groupingBy(side -> side,
- summingDouble(n -> fraction)));
- }
- private static long timeIt(Runnable toTime) {
- final long start = System.currentTimeMillis();
- toTime.run();
- final long stop = System.currentTimeMillis();
- return (stop - start);
- }
- @Test
- public static void main(String[] args) throws Exception {
- // warm thread locals
- parallelDiceRolls(0);
- parallelDiceRolls(0);
- final List<Long> sizesToTry = ImmutableList.of(100L, 1_000L, 10_000L, 100_000L, 1_000_000L, 10_000_000L, 100_000_000L);
- for (long n : sizesToTry) {
- final long parallelExecutionTime = timeIt(() -> parallelDiceRolls(n));
- final long serialExecutionTime = timeIt(() -> serialDiceRolls(n));
- System.out.println(String.format("For simulation size %9d, serial took %4d millis and parallel took %4d millis",
- n, serialExecutionTime, parallelExecutionTime));
- }
- /*
- For simulation size 100, serial took 1 millis and parallel took 2 millis
- For simulation size 1000, serial took 2 millis and parallel took 2 millis
- For simulation size 10000, serial took 5 millis and parallel took 4 millis
- For simulation size 100000, serial took 5 millis and parallel took 8 millis
- For simulation size 1000000, serial took 28 millis and parallel took 40 millis
- For simulation size 10000000, serial took 181 millis and parallel took 45 millis
- For simulation size 100000000, serial took 1878 millis and parallel took 577 millis
- */
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement