ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/loops/TimeUnitLoops.java
Revision: 1.2
Committed: Sat Feb 16 21:37:44 2013 UTC (11 years, 4 months ago) by jsr166
Branch: MAIN
Changes since 1.1: +6 -0 lines
Log Message:
add missing public domain notices

File Contents

# User Rev Content
1 jsr166 1.2 /*
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 peierls 1.1 import java.util.concurrent.*;
8     import java.util.Random;
9    
10     public class TimeUnitLoops {
11    
12     static final LoopHelpers.SimpleRandom rng = new LoopHelpers.SimpleRandom();
13    
14     /**
15     * False value allows aggressive inlining of cvt() calls from
16     * test(). True value prevents any inlining, requiring virtual
17     * method dispatch.
18     */
19     static final boolean PREVENT_INLINING = true;
20    
21     // The following all are used by inlining prevention clause:
22     static int index = 0;
23     static final int NUNITS = 100;
24     static final TimeUnit[] units = new TimeUnit[NUNITS];
25     static {
26     TimeUnit[] v = TimeUnit.values();
27     for (int i = 0; i < NUNITS; ++i)
28     units[i] = v[rng.next() % v.length];
29     }
30    
31     public static void main(String[] args) throws Exception {
32     long start = System.currentTimeMillis();
33     long s = 0;
34     for (int i = 0; i < 100; ++i) {
35     s += test();
36     if (s == start) System.out.println(" ");
37     }
38     long end = System.currentTimeMillis();
39     System.out.println("Time: " + (end - start) + " ms");
40     }
41    
42     static long test() {
43     long sum = 0;
44     int x = rng.next();
45     for (int i = 0; i < 1000000; ++i) {
46     long l = (long)x + (long)x;
47     sum += cvt(l, TimeUnit.SECONDS);
48     sum += TimeUnit.MILLISECONDS.toMicros(l+2);
49     sum += cvt(l+17, TimeUnit.NANOSECONDS);
50     sum += cvt(l+42, TimeUnit.MILLISECONDS);
51     x = LoopHelpers.compute4(x);
52     }
53     return sum + x;
54     }
55    
56     static long cvt(long d, TimeUnit u) {
57     if (PREVENT_INLINING) {
58     u = units[index];
59     index = (index+1) % NUNITS;
60     }
61    
62     return u.toNanos(d);
63     }
64     }