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 |
jsr166 |
1.6 |
* http://creativecommons.org/publicdomain/zero/1.0/ |
5 |
dl |
1.1 |
*/ |
6 |
|
|
|
7 |
|
|
import jsr166y.*; |
8 |
|
|
import extra166y.*; |
9 |
|
|
import java.util.*; |
10 |
|
|
|
11 |
|
|
class SortDemo { |
12 |
|
|
|
13 |
|
|
static final Random rng = new Random(); |
14 |
|
|
static final long NPS = (1000L * 1000 * 1000); |
15 |
|
|
|
16 |
dl |
1.5 |
public static void main (String[] args) throws Exception { |
17 |
|
|
int n = 1 << 22; |
18 |
dl |
1.1 |
int sreps = 4; |
19 |
|
|
int reps = 20; |
20 |
|
|
Long[] a = new Long[n]; |
21 |
|
|
ForkJoinPool fjpool = new ForkJoinPool(); |
22 |
|
|
ParallelArray<Long> pa = ParallelArray.createUsingHandoff(a, fjpool); |
23 |
|
|
|
24 |
|
|
System.out.printf("Parallel Sort %d Longs, %d replications\n", n, reps); |
25 |
|
|
for (int i = 0; i < reps; ++i) { |
26 |
|
|
pa.replaceWithGeneratedValue(rlg); |
27 |
|
|
parSort(pa); |
28 |
|
|
if (i == 0) |
29 |
|
|
checkSorted(a); |
30 |
|
|
} |
31 |
|
|
System.out.printf("Sequential Sort %d Longs, %d replications\n", n, sreps); |
32 |
|
|
for (int i = 0; i < sreps; ++i) { |
33 |
|
|
pa.replaceWithGeneratedValue(rlg); |
34 |
|
|
seqSort(a); |
35 |
|
|
if (i == 0) |
36 |
|
|
checkSorted(a); |
37 |
|
|
} |
38 |
|
|
|
39 |
|
|
System.out.println(fjpool); |
40 |
|
|
fjpool.shutdown(); |
41 |
|
|
} |
42 |
jsr166 |
1.2 |
|
43 |
dl |
1.1 |
static void seqSort(Long[] a) { |
44 |
|
|
long last = System.nanoTime(); |
45 |
|
|
java.util.Arrays.sort(a); |
46 |
|
|
double elapsed = (double)(System.nanoTime() - last) / NPS; |
47 |
|
|
System.out.printf("java.util.Arrays.sort time: %7.3f\n", elapsed); |
48 |
|
|
} |
49 |
|
|
|
50 |
|
|
static void parSort(ParallelArray<Long> pa) { |
51 |
|
|
long last = System.nanoTime(); |
52 |
|
|
pa.sort(); |
53 |
|
|
double elapsed = (double)(System.nanoTime() - last) / NPS; |
54 |
|
|
System.out.printf("ParallelArray.sort time: %7.3f\n", elapsed); |
55 |
|
|
} |
56 |
jsr166 |
1.2 |
|
57 |
jsr166 |
1.4 |
static void checkSorted(Long[] a) { |
58 |
dl |
1.1 |
int n = a.length; |
59 |
|
|
for (int i = 0; i < n - 1; i++) { |
60 |
|
|
if (a[i].compareTo(a[i+1]) > 0) { |
61 |
|
|
throw new Error("Unsorted at " + i + ": " + a[i] + " / " + a[i+1]); |
62 |
|
|
} |
63 |
|
|
} |
64 |
|
|
} |
65 |
jsr166 |
1.2 |
|
66 |
dl |
1.1 |
static final class RandomLongGenerator implements Ops.Generator<Long> { |
67 |
|
|
public Long op() { |
68 |
|
|
return new Long(ThreadLocalRandom.current().nextLong()); |
69 |
|
|
} |
70 |
|
|
} |
71 |
|
|
|
72 |
|
|
static final RandomLongGenerator rlg = new RandomLongGenerator(); |
73 |
|
|
|
74 |
|
|
|
75 |
|
|
|
76 |
|
|
} |