1 |
/* |
2 |
* Copyright (c) 2007, Oracle and/or its affiliates. All rights reserved. |
3 |
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. |
4 |
* |
5 |
* This code is free software; you can redistribute it and/or modify it |
6 |
* under the terms of the GNU General Public License version 2 only, as |
7 |
* published by the Free Software Foundation. |
8 |
* |
9 |
* This code is distributed in the hope that it will be useful, but WITHOUT |
10 |
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or |
11 |
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License |
12 |
* version 2 for more details (a copy is included in the LICENSE file that |
13 |
* accompanied this code). |
14 |
* |
15 |
* You should have received a copy of the GNU General Public License version |
16 |
* 2 along with this work; if not, write to the Free Software Foundation, |
17 |
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. |
18 |
* |
19 |
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA |
20 |
* or visit www.oracle.com if you need additional information or have any |
21 |
* questions. |
22 |
*/ |
23 |
|
24 |
/* |
25 |
* @test |
26 |
* @summary micro-benchmark correctness mode |
27 |
* @run main IteratorMicroBenchmark iterations=1 size=8 warmup=0 |
28 |
*/ |
29 |
|
30 |
import java.lang.ref.WeakReference; |
31 |
import java.util.ArrayDeque; |
32 |
import java.util.Arrays; |
33 |
import java.util.ArrayList; |
34 |
import java.util.Collection; |
35 |
import java.util.Collections; |
36 |
import java.util.Deque; |
37 |
import java.util.Enumeration; |
38 |
import java.util.Iterator; |
39 |
import java.util.List; |
40 |
import java.util.ListIterator; |
41 |
import java.util.Map; |
42 |
import java.util.PriorityQueue; |
43 |
import java.util.Spliterator; |
44 |
import java.util.Vector; |
45 |
import java.util.concurrent.ArrayBlockingQueue; |
46 |
import java.util.concurrent.ConcurrentLinkedDeque; |
47 |
import java.util.concurrent.ConcurrentLinkedQueue; |
48 |
import java.util.concurrent.LinkedBlockingDeque; |
49 |
import java.util.concurrent.LinkedBlockingQueue; |
50 |
import java.util.concurrent.LinkedTransferQueue; |
51 |
import java.util.concurrent.PriorityBlockingQueue; |
52 |
import java.util.concurrent.ConcurrentSkipListMap; |
53 |
import java.util.concurrent.CountDownLatch; |
54 |
import java.util.concurrent.ThreadLocalRandom; |
55 |
import java.util.concurrent.TimeUnit; |
56 |
import java.util.regex.Pattern; |
57 |
|
58 |
/** |
59 |
* Usage: [iterations=N] [size=N] [filter=REGEXP] [warmup=SECONDS] |
60 |
* |
61 |
* To run this in micro-benchmark mode, simply run as a normal java program. |
62 |
* Be patient; this program runs for a very long time. |
63 |
* For faster runs, restrict execution using command line args. |
64 |
* |
65 |
* This is an interface based version of ArrayList/IteratorMicroBenchmark |
66 |
* |
67 |
* @author Martin Buchholz |
68 |
*/ |
69 |
public class IteratorMicroBenchmark { |
70 |
abstract static class Job { |
71 |
private final String name; |
72 |
public Job(String name) { this.name = name; } |
73 |
public String name() { return name; } |
74 |
public abstract void work() throws Throwable; |
75 |
} |
76 |
|
77 |
final int iterations; |
78 |
final int size; // number of elements in collections |
79 |
final double warmupSeconds; |
80 |
final long warmupNanos; |
81 |
final Pattern filter; // select subset of Jobs to run |
82 |
final boolean reverse; // reverse order of Jobs |
83 |
final boolean shuffle; // randomize order of Jobs |
84 |
|
85 |
IteratorMicroBenchmark(String[] args) { |
86 |
iterations = intArg(args, "iterations", 10_000); |
87 |
size = intArg(args, "size", 1000); |
88 |
warmupSeconds = doubleArg(args, "warmup", 7.0); |
89 |
filter = patternArg(args, "filter"); |
90 |
reverse = booleanArg(args, "reverse"); |
91 |
shuffle = booleanArg(args, "shuffle"); |
92 |
|
93 |
warmupNanos = (long) (warmupSeconds * (1000L * 1000L * 1000L)); |
94 |
} |
95 |
|
96 |
// --------------- GC finalization infrastructure --------------- |
97 |
|
98 |
/** No guarantees, but effective in practice. */ |
99 |
static void forceFullGc() { |
100 |
CountDownLatch finalizeDone = new CountDownLatch(1); |
101 |
WeakReference<?> ref = new WeakReference<Object>(new Object() { |
102 |
protected void finalize() { finalizeDone.countDown(); }}); |
103 |
try { |
104 |
for (int i = 0; i < 10; i++) { |
105 |
System.gc(); |
106 |
if (finalizeDone.await(1L, TimeUnit.SECONDS) && ref.get() == null) { |
107 |
System.runFinalization(); // try to pick up stragglers |
108 |
return; |
109 |
} |
110 |
} |
111 |
} catch (InterruptedException unexpected) { |
112 |
throw new AssertionError("unexpected InterruptedException"); |
113 |
} |
114 |
throw new AssertionError("failed to do a \"full\" gc"); |
115 |
} |
116 |
|
117 |
/** |
118 |
* Runs each job for long enough that all the runtime compilers |
119 |
* have had plenty of time to warm up, i.e. get around to |
120 |
* compiling everything worth compiling. |
121 |
* Returns array of average times per job per run. |
122 |
*/ |
123 |
long[] time0(List<Job> jobs) throws Throwable { |
124 |
final int size = jobs.size(); |
125 |
long[] nanoss = new long[size]; |
126 |
for (int i = 0; i < size; i++) { |
127 |
if (warmupNanos > 0) forceFullGc(); |
128 |
Job job = jobs.get(i); |
129 |
long totalTime; |
130 |
int runs = 0; |
131 |
long startTime = System.nanoTime(); |
132 |
do { job.work(); runs++; } |
133 |
while ((totalTime = System.nanoTime() - startTime) < warmupNanos); |
134 |
nanoss[i] = totalTime/runs; |
135 |
} |
136 |
return nanoss; |
137 |
} |
138 |
|
139 |
void time(List<Job> jobs) throws Throwable { |
140 |
if (warmupNanos > 0) time0(jobs); // Warm up run |
141 |
final int size = jobs.size(); |
142 |
final long[] nanoss = time0(jobs); // Real timing run |
143 |
final long[] milliss = new long[size]; |
144 |
final double[] ratios = new double[size]; |
145 |
|
146 |
final String nameHeader = "Method"; |
147 |
final String millisHeader = "Millis"; |
148 |
final String ratioHeader = "Ratio"; |
149 |
|
150 |
int nameWidth = nameHeader.length(); |
151 |
int millisWidth = millisHeader.length(); |
152 |
int ratioWidth = ratioHeader.length(); |
153 |
|
154 |
for (int i = 0; i < size; i++) { |
155 |
nameWidth = Math.max(nameWidth, jobs.get(i).name().length()); |
156 |
|
157 |
milliss[i] = nanoss[i]/(1000L * 1000L); |
158 |
millisWidth = Math.max(millisWidth, |
159 |
String.format("%d", milliss[i]).length()); |
160 |
|
161 |
ratios[i] = (double) nanoss[i] / (double) nanoss[0]; |
162 |
ratioWidth = Math.max(ratioWidth, |
163 |
String.format("%.3f", ratios[i]).length()); |
164 |
} |
165 |
|
166 |
String format = String.format("%%-%ds %%%dd %%%d.3f%%n", |
167 |
nameWidth, millisWidth, ratioWidth); |
168 |
String headerFormat = String.format("%%-%ds %%%ds %%%ds%%n", |
169 |
nameWidth, millisWidth, ratioWidth); |
170 |
System.out.printf(headerFormat, "Method", "Millis", "Ratio"); |
171 |
|
172 |
// Print out absolute and relative times, calibrated against first job |
173 |
for (int i = 0; i < size; i++) |
174 |
System.out.printf(format, jobs.get(i).name(), milliss[i], ratios[i]); |
175 |
} |
176 |
|
177 |
private static String keywordValue(String[] args, String keyword) { |
178 |
for (String arg : args) |
179 |
if (arg.startsWith(keyword)) |
180 |
return arg.substring(keyword.length() + 1); |
181 |
return null; |
182 |
} |
183 |
|
184 |
private static int intArg(String[] args, String keyword, int defaultValue) { |
185 |
String val = keywordValue(args, keyword); |
186 |
return (val == null) ? defaultValue : Integer.parseInt(val); |
187 |
} |
188 |
|
189 |
private static double doubleArg(String[] args, String keyword, double defaultValue) { |
190 |
String val = keywordValue(args, keyword); |
191 |
return (val == null) ? defaultValue : Double.parseDouble(val); |
192 |
} |
193 |
|
194 |
private static Pattern patternArg(String[] args, String keyword) { |
195 |
String val = keywordValue(args, keyword); |
196 |
return (val == null) ? null : Pattern.compile(val); |
197 |
} |
198 |
|
199 |
private static boolean booleanArg(String[] args, String keyword) { |
200 |
String val = keywordValue(args, keyword); |
201 |
if (val == null || val.equals("false")) return false; |
202 |
if (val.equals("true")) return true; |
203 |
throw new IllegalArgumentException(val); |
204 |
} |
205 |
|
206 |
private static List<Job> filter(Pattern filter, List<Job> jobs) { |
207 |
if (filter == null) return jobs; |
208 |
ArrayList<Job> newJobs = new ArrayList<>(); |
209 |
for (Job job : jobs) |
210 |
if (filter.matcher(job.name()).find()) |
211 |
newJobs.add(job); |
212 |
return newJobs; |
213 |
} |
214 |
|
215 |
private static void deoptimize(int sum) { |
216 |
if (sum == 42) |
217 |
System.out.println("the answer"); |
218 |
} |
219 |
|
220 |
private static <T> List<T> asSubList(List<T> list) { |
221 |
return list.subList(0, list.size()); |
222 |
} |
223 |
|
224 |
private static <T> Iterable<T> backwards(final List<T> list) { |
225 |
return new Iterable<T>() { |
226 |
public Iterator<T> iterator() { |
227 |
return new Iterator<T>() { |
228 |
final ListIterator<T> it = list.listIterator(list.size()); |
229 |
public boolean hasNext() { return it.hasPrevious(); } |
230 |
public T next() { return it.previous(); } |
231 |
public void remove() { it.remove(); }};}}; |
232 |
} |
233 |
|
234 |
// Checks for correctness *and* prevents loop optimizations |
235 |
class Check { |
236 |
private int sum; |
237 |
public void sum(int sum) { |
238 |
if (this.sum == 0) |
239 |
this.sum = sum; |
240 |
if (this.sum != sum) |
241 |
throw new AssertionError("Sum mismatch"); |
242 |
} |
243 |
} |
244 |
volatile Check check = new Check(); |
245 |
|
246 |
public static void main(String[] args) throws Throwable { |
247 |
new IteratorMicroBenchmark(args).run(); |
248 |
} |
249 |
|
250 |
void run() throws Throwable { |
251 |
// System.out.printf( |
252 |
// "iterations=%d size=%d, warmup=%1g, filter=\"%s\"%n", |
253 |
// iterations, size, warmupSeconds, filter); |
254 |
|
255 |
final ArrayList<Integer> al = new ArrayList<Integer>(size); |
256 |
|
257 |
// Populate collections with random data |
258 |
final ThreadLocalRandom rnd = ThreadLocalRandom.current(); |
259 |
for (int i = 0; i < size; i++) |
260 |
al.add(rnd.nextInt(size)); |
261 |
|
262 |
final ArrayDeque<Integer> ad = new ArrayDeque<>(al); |
263 |
final ArrayBlockingQueue<Integer> abq = new ArrayBlockingQueue<>(al.size()); |
264 |
abq.addAll(al); |
265 |
|
266 |
// shuffle circular array elements so they wrap |
267 |
for (int i = 0, n = rnd.nextInt(size); i < n; i++) { |
268 |
ad.addLast(ad.removeFirst()); |
269 |
abq.add(abq.remove()); |
270 |
} |
271 |
|
272 |
ArrayList<Job> jobs = new ArrayList<>(Arrays.asList()); |
273 |
|
274 |
List.of(al, ad, abq, |
275 |
new PriorityQueue<>(al), |
276 |
new Vector<>(al), |
277 |
new ConcurrentLinkedQueue<>(al), |
278 |
new ConcurrentLinkedDeque<>(al), |
279 |
new LinkedBlockingQueue<>(al), |
280 |
new LinkedBlockingDeque<>(al), |
281 |
new LinkedTransferQueue<>(al), |
282 |
new PriorityBlockingQueue<>(al)) |
283 |
.stream() |
284 |
.forEach(x -> { |
285 |
jobs.addAll(collectionJobs(x)); |
286 |
if (x instanceof Deque) |
287 |
jobs.addAll(dequeJobs((Deque<Integer>)x)); |
288 |
}); |
289 |
|
290 |
if (reverse) Collections.reverse(jobs); |
291 |
if (shuffle) Collections.shuffle(jobs); |
292 |
|
293 |
time(filter(filter, jobs)); |
294 |
} |
295 |
|
296 |
List<Job> collectionJobs(Collection<Integer> x) { |
297 |
String klazz = x.getClass().getSimpleName(); |
298 |
return List.of( |
299 |
new Job(klazz + " iterate for loop") { |
300 |
public void work() throws Throwable { |
301 |
for (int i = 0; i < iterations; i++) { |
302 |
int sum = 0; |
303 |
for (Integer n : x) |
304 |
sum += n; |
305 |
check.sum(sum);}}}, |
306 |
new Job(klazz + " .iterator().forEachRemaining()") { |
307 |
public void work() throws Throwable { |
308 |
int[] sum = new int[1]; |
309 |
for (int i = 0; i < iterations; i++) { |
310 |
sum[0] = 0; |
311 |
x.iterator().forEachRemaining(n -> sum[0] += n); |
312 |
check.sum(sum[0]);}}}, |
313 |
new Job(klazz + " .spliterator().tryAdvance()") { |
314 |
public void work() throws Throwable { |
315 |
int[] sum = new int[1]; |
316 |
for (int i = 0; i < iterations; i++) { |
317 |
sum[0] = 0; |
318 |
Spliterator<Integer> spliterator = x.spliterator(); |
319 |
do {} while (spliterator.tryAdvance(n -> sum[0] += n)); |
320 |
check.sum(sum[0]);}}}, |
321 |
new Job(klazz + " .spliterator().forEachRemaining()") { |
322 |
public void work() throws Throwable { |
323 |
int[] sum = new int[1]; |
324 |
for (int i = 0; i < iterations; i++) { |
325 |
sum[0] = 0; |
326 |
x.spliterator().forEachRemaining(n -> sum[0] += n); |
327 |
check.sum(sum[0]);}}}, |
328 |
new Job(klazz + " .removeIf") { |
329 |
public void work() throws Throwable { |
330 |
int[] sum = new int[1]; |
331 |
for (int i = 0; i < iterations; i++) { |
332 |
sum[0] = 0; |
333 |
x.removeIf(n -> { sum[0] += n; return false; }); |
334 |
check.sum(sum[0]);}}}, |
335 |
new Job(klazz + " .forEach") { |
336 |
public void work() throws Throwable { |
337 |
int[] sum = new int[1]; |
338 |
for (int i = 0; i < iterations; i++) { |
339 |
sum[0] = 0; |
340 |
x.forEach(n -> sum[0] += n); |
341 |
check.sum(sum[0]);}}}, |
342 |
new Job(klazz + " .toArray()") { |
343 |
public void work() throws Throwable { |
344 |
int[] sum = new int[1]; |
345 |
for (int i = 0; i < iterations; i++) { |
346 |
sum[0] = 0; |
347 |
for (Object o : x.toArray()) |
348 |
sum[0] += (Integer) o; |
349 |
check.sum(sum[0]);}}}, |
350 |
new Job(klazz + " .toArray(a)") { |
351 |
public void work() throws Throwable { |
352 |
Integer[] a = new Integer[x.size()]; |
353 |
int[] sum = new int[1]; |
354 |
for (int i = 0; i < iterations; i++) { |
355 |
sum[0] = 0; |
356 |
x.toArray(a); |
357 |
for (Object o : a) |
358 |
sum[0] += (Integer) o; |
359 |
check.sum(sum[0]);}}}, |
360 |
new Job(klazz + " .toArray(empty)") { |
361 |
public void work() throws Throwable { |
362 |
Integer[] empty = new Integer[0]; |
363 |
int[] sum = new int[1]; |
364 |
for (int i = 0; i < iterations; i++) { |
365 |
sum[0] = 0; |
366 |
for (Integer o : x.toArray(empty)) |
367 |
sum[0] += o; |
368 |
check.sum(sum[0]);}}}); |
369 |
} |
370 |
|
371 |
List<Job> dequeJobs(Deque<Integer> x) { |
372 |
String klazz = x.getClass().getSimpleName(); |
373 |
return List.of( |
374 |
new Job(klazz + " .descendingIterator() loop") { |
375 |
public void work() throws Throwable { |
376 |
for (int i = 0; i < iterations; i++) { |
377 |
int sum = 0; |
378 |
Iterator<Integer> it = x.descendingIterator(); |
379 |
while (it.hasNext()) |
380 |
sum += it.next(); |
381 |
check.sum(sum);}}}, |
382 |
new Job(klazz + " .descendingIterator().forEachRemaining()") { |
383 |
public void work() throws Throwable { |
384 |
int[] sum = new int[1]; |
385 |
for (int i = 0; i < iterations; i++) { |
386 |
sum[0] = 0; |
387 |
x.descendingIterator().forEachRemaining(n -> sum[0] += n); |
388 |
check.sum(sum[0]);}}}); |
389 |
} |
390 |
} |