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