ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/test/loops/LongAdderLoops.java
Revision: 1.1
Committed: Mon Jan 26 14:23:10 2015 UTC (9 years, 3 months ago) by dl
Branch: MAIN
Log Message:
Convert jsr166e version

File Contents

# User Rev Content
1 dl 1.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.*;
8     import java.util.concurrent.atomic.LongAdder;
9     import java.util.concurrent.Executors;
10     import java.util.concurrent.ExecutorService;
11     import java.util.concurrent.Phaser;
12    
13     public class LongAdderLoops {
14     static final int ITERS = 10000000;
15     static final int NCPU = Runtime.getRuntime().availableProcessors();
16     static final int MAX_THREADS = NCPU * 2;
17     static final long NPS = (1000L * 1000 * 1000);
18    
19     static final ExecutorService pool = Executors.newCachedThreadPool();
20    
21     public static void main(String[] args) {
22     for (int i = 1; i < MAX_THREADS; ++i)
23     adderTest(i, ITERS);
24     pool.shutdown();
25     }
26    
27     static void adderTest(int nthreads, int incs) {
28     System.out.print("LongAdder ");
29     Phaser phaser = new Phaser(nthreads + 1);
30     LongAdder a = new LongAdder();
31     for (int i = 0; i < nthreads; ++i)
32     pool.execute(new AdderTask(a, phaser, incs));
33     report(nthreads, incs, timeTasks(phaser), a.sum());
34     }
35    
36     static void report(int nthreads, int incs, long time, long sum) {
37     long total = (long)nthreads * incs;
38     if (sum != total)
39     throw new Error(sum + " != " + total);
40     double secs = (double)time / (1000L * 1000 * 1000);
41     long rate = total * (1000L) / time;
42     System.out.printf("threads:%3d Time: %7.3fsec Incs per microsec: %4d\n",
43     nthreads, secs, rate);
44     }
45    
46     static long timeTasks(Phaser phaser) {
47     phaser.arriveAndAwaitAdvance();
48     long start = System.nanoTime();
49     phaser.arriveAndAwaitAdvance();
50     phaser.arriveAndAwaitAdvance();
51     return System.nanoTime() - start;
52     }
53    
54     static final class AdderTask implements Runnable {
55     final LongAdder adder;
56     final Phaser phaser;
57     final int incs;
58     volatile long result;
59     AdderTask(LongAdder adder, Phaser phaser, int incs) {
60     this.adder = adder;
61     this.phaser = phaser;
62     this.incs = incs;
63     }
64    
65     public void run() {
66     phaser.arriveAndAwaitAdvance();
67     phaser.arriveAndAwaitAdvance();
68     LongAdder a = adder;
69     for (int i = 0; i < incs; ++i)
70     a.increment();
71     result = a.sum();
72     phaser.arrive();
73     }
74     }
75    
76     }