ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/test/loops/LongAdderLoops.java
Revision: 1.4
Committed: Mon Jan 26 17:30:04 2015 UTC (9 years, 3 months ago) by jsr166
Branch: MAIN
Changes since 1.3: +1 -2 lines
Log Message:
remove unused var NPS; bump up ITERS

File Contents

# Content
1 /*
2 * Written by Doug Lea with assistance from members of JCP JSR-166
3 * Expert Group and released to the public domain, as explained at
4 * http://creativecommons.org/publicdomain/zero/1.0/
5 */
6
7 import java.util.concurrent.atomic.LongAdder;
8 import java.util.concurrent.Executors;
9 import java.util.concurrent.ExecutorService;
10 import java.util.concurrent.Phaser;
11
12 public class LongAdderLoops {
13 static final int ITERS = 100_000_000;
14 static final int NCPU = Runtime.getRuntime().availableProcessors();
15 static final int MAX_THREADS = NCPU * 2;
16
17 static final ExecutorService pool = Executors.newCachedThreadPool();
18
19 public static void main(String[] args) {
20 for (int i = 1; i < MAX_THREADS; ++i)
21 adderTest(i, ITERS);
22 pool.shutdown();
23 }
24
25 static void adderTest(int nthreads, int incs) {
26 System.out.print("LongAdder ");
27 Phaser phaser = new Phaser(nthreads + 1);
28 LongAdder a = new LongAdder();
29 for (int i = 0; i < nthreads; ++i)
30 pool.execute(new AdderTask(a, phaser, incs));
31 report(nthreads, incs, timeTasks(phaser), a.sum());
32 }
33
34 static void report(int nthreads, int incs, long time, long sum) {
35 long total = (long)nthreads * incs;
36 if (sum != total)
37 throw new Error(sum + " != " + total);
38 double secs = (double)time / (1000L * 1000 * 1000);
39 long rate = total * (1000L) / time;
40 System.out.printf("threads:%3d Time: %7.3fsec Incs per microsec: %4d\n",
41 nthreads, secs, rate);
42 }
43
44 static long timeTasks(Phaser phaser) {
45 phaser.arriveAndAwaitAdvance();
46 long start = System.nanoTime();
47 phaser.arriveAndAwaitAdvance();
48 phaser.arriveAndAwaitAdvance();
49 return System.nanoTime() - start;
50 }
51
52 static final class AdderTask implements Runnable {
53 final LongAdder adder;
54 final Phaser phaser;
55 final int incs;
56 volatile long result;
57 AdderTask(LongAdder adder, Phaser phaser, int incs) {
58 this.adder = adder;
59 this.phaser = phaser;
60 this.incs = incs;
61 }
62
63 public void run() {
64 phaser.arriveAndAwaitAdvance();
65 phaser.arriveAndAwaitAdvance();
66 LongAdder a = adder;
67 for (int i = 0; i < incs; ++i)
68 a.increment();
69 result = a.sum();
70 phaser.arrive();
71 }
72 }
73
74 }