Advertisement
Guest User

Untitled

a guest
Sep 21st, 2017
70
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.53 KB | None | 0 0
  1. /**
  2. * simulates throwing two dice
  3. * @return the sum of the two die
  4. */
  5. private static int twoDiceThrows() {
  6. final int dieA = ThreadLocalRandom.current().nextInt(5) + 1;
  7. final int dieB = ThreadLocalRandom.current().nextInt(5) + 1;
  8. return dieA + dieB;
  9. }
  10.  
  11. private static Map<Integer, Double> serialDiceRolls(long N) {
  12. double fraction = 1.0 / N;
  13. return LongStream.range(0, N)
  14. .mapToObj((i) -> twoDiceThrows())
  15. .collect(groupingBy(side -> side,
  16. summingDouble(n -> fraction)));
  17. }
  18.  
  19. private static Map<Integer, Double> parallelDiceRolls(long N) {
  20. double fraction = 1.0 / N;
  21. return LongStream.range(0, N)
  22. .parallel() // *
  23. .mapToObj((i) -> twoDiceThrows())
  24. .collect(groupingBy(side -> side,
  25. summingDouble(n -> fraction)));
  26. }
  27.  
  28. private static long timeIt(Runnable toTime) {
  29. final long start = System.currentTimeMillis();
  30. toTime.run();
  31. final long stop = System.currentTimeMillis();
  32. return (stop - start);
  33. }
  34.  
  35. @Test
  36. public static void main(String[] args) throws Exception {
  37.  
  38. // warm thread locals
  39. parallelDiceRolls(0);
  40. parallelDiceRolls(0);
  41.  
  42. final List<Long> sizesToTry = ImmutableList.of(100L, 1_000L, 10_000L, 100_000L, 1_000_000L, 10_000_000L, 100_000_000L);
  43.  
  44. for (long n : sizesToTry) {
  45. final long parallelExecutionTime = timeIt(() -> parallelDiceRolls(n));
  46. final long serialExecutionTime = timeIt(() -> serialDiceRolls(n));
  47. System.out.println(String.format("For simulation size %9d, serial took %4d millis and parallel took %4d millis",
  48. n, serialExecutionTime, parallelExecutionTime));
  49.  
  50. }
  51.  
  52. /*
  53. For simulation size 100, serial took 1 millis and parallel took 2 millis
  54. For simulation size 1000, serial took 2 millis and parallel took 2 millis
  55. For simulation size 10000, serial took 5 millis and parallel took 4 millis
  56. For simulation size 100000, serial took 5 millis and parallel took 8 millis
  57. For simulation size 1000000, serial took 28 millis and parallel took 40 millis
  58. For simulation size 10000000, serial took 181 millis and parallel took 45 millis
  59. For simulation size 100000000, serial took 1878 millis and parallel took 577 millis
  60. */
  61.  
  62. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement