ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/test/jtreg/util/Collection/IteratorMicroBenchmark.java
Revision: 1.29
Committed: Sun Jan 7 21:11:41 2018 UTC (6 years, 4 months ago) by jsr166
Branch: MAIN
Changes since 1.28: +0 -1 lines
Log Message:
remove unused import

File Contents

# Content
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 static java.util.stream.Collectors.summingInt;
31 import static java.util.stream.Collectors.toList;
32
33 import java.lang.ref.WeakReference;
34 import java.util.ArrayDeque;
35 import java.util.ArrayList;
36 import java.util.Collection;
37 import java.util.Collections;
38 import java.util.Deque;
39 import java.util.Iterator;
40 import java.util.LinkedList;
41 import java.util.List;
42 import java.util.ListIterator;
43 import java.util.PriorityQueue;
44 import java.util.Spliterator;
45 import java.util.Vector;
46 import java.util.concurrent.ArrayBlockingQueue;
47 import java.util.concurrent.ConcurrentLinkedDeque;
48 import java.util.concurrent.ConcurrentLinkedQueue;
49 import java.util.concurrent.LinkedBlockingDeque;
50 import java.util.concurrent.LinkedBlockingQueue;
51 import java.util.concurrent.LinkedTransferQueue;
52 import java.util.concurrent.PriorityBlockingQueue;
53 import java.util.concurrent.CountDownLatch;
54 import java.util.concurrent.ThreadLocalRandom;
55 import java.util.concurrent.TimeUnit;
56 import java.util.concurrent.atomic.LongAdder;
57 import java.util.regex.Pattern;
58
59 /**
60 * Usage: [iterations=N] [size=N] [filter=REGEXP] [warmup=SECONDS]
61 *
62 * To run this in micro-benchmark mode, simply run as a normal java program.
63 * Be patient; this program runs for a very long time.
64 * For faster runs, restrict execution using command line args.
65 *
66 * This is an interface based version of ArrayList/IteratorMicroBenchmark
67 *
68 * @author Martin Buchholz
69 */
70 public class IteratorMicroBenchmark {
71 abstract static class Job {
72 private final String name;
73 public Job(String name) { this.name = name; }
74 public String name() { return name; }
75 public abstract void work() throws Throwable;
76 }
77
78 final int iterations;
79 final int size; // number of elements in collections
80 final double warmupSeconds;
81 final long warmupNanos;
82 final Pattern filter; // select subset of Jobs to run
83 final boolean reverse; // reverse order of Jobs
84 final boolean shuffle; // randomize order of Jobs
85
86 IteratorMicroBenchmark(String[] args) {
87 iterations = intArg(args, "iterations", 10_000);
88 size = intArg(args, "size", 1000);
89 warmupSeconds = doubleArg(args, "warmup", 7.0);
90 filter = patternArg(args, "filter");
91 reverse = booleanArg(args, "reverse");
92 shuffle = booleanArg(args, "shuffle");
93
94 warmupNanos = (long) (warmupSeconds * (1000L * 1000L * 1000L));
95 }
96
97 // --------------- GC finalization infrastructure ---------------
98
99 /** No guarantees, but effective in practice. */
100 static void forceFullGc() {
101 CountDownLatch finalizeDone = new CountDownLatch(1);
102 WeakReference<?> ref = new WeakReference<Object>(new Object() {
103 protected void finalize() { finalizeDone.countDown(); }});
104 try {
105 for (int i = 0; i < 10; i++) {
106 System.gc();
107 if (finalizeDone.await(1L, TimeUnit.SECONDS) && ref.get() == null) {
108 System.runFinalization(); // try to pick up stragglers
109 return;
110 }
111 }
112 } catch (InterruptedException unexpected) {
113 throw new AssertionError("unexpected InterruptedException");
114 }
115 throw new AssertionError("failed to do a \"full\" gc");
116 }
117
118 /**
119 * Runs each job for long enough that all the runtime compilers
120 * have had plenty of time to warm up, i.e. get around to
121 * compiling everything worth compiling.
122 * Returns array of average times per job per run.
123 */
124 long[] time0(List<Job> jobs) throws Throwable {
125 final int size = jobs.size();
126 long[] nanoss = new long[size];
127 for (int i = 0; i < size; i++) {
128 if (warmupNanos > 0) forceFullGc();
129 Job job = jobs.get(i);
130 long totalTime;
131 int runs = 0;
132 long startTime = System.nanoTime();
133 do { job.work(); runs++; }
134 while ((totalTime = System.nanoTime() - startTime) < warmupNanos);
135 nanoss[i] = totalTime/runs;
136 }
137 return nanoss;
138 }
139
140 void time(List<Job> jobs) throws Throwable {
141 if (warmupNanos > 0) time0(jobs); // Warm up run
142 final int size = jobs.size();
143 final long[] nanoss = time0(jobs); // Real timing run
144 final long[] milliss = new long[size];
145 final double[] ratios = new double[size];
146
147 final String nameHeader = "Method";
148 final String millisHeader = "Millis";
149 final String ratioHeader = "Ratio";
150
151 int nameWidth = nameHeader.length();
152 int millisWidth = millisHeader.length();
153 int ratioWidth = ratioHeader.length();
154
155 for (int i = 0; i < size; i++) {
156 nameWidth = Math.max(nameWidth, jobs.get(i).name().length());
157
158 milliss[i] = nanoss[i]/(1000L * 1000L);
159 millisWidth = Math.max(millisWidth,
160 String.format("%d", milliss[i]).length());
161
162 ratios[i] = (double) nanoss[i] / (double) nanoss[0];
163 ratioWidth = Math.max(ratioWidth,
164 String.format("%.3f", ratios[i]).length());
165 }
166
167 String format = String.format("%%-%ds %%%dd %%%d.3f%%n",
168 nameWidth, millisWidth, ratioWidth);
169 String headerFormat = String.format("%%-%ds %%%ds %%%ds%%n",
170 nameWidth, millisWidth, ratioWidth);
171 System.out.printf(headerFormat, "Method", "Millis", "Ratio");
172
173 // Print out absolute and relative times, calibrated against first job
174 for (int i = 0; i < size; i++)
175 System.out.printf(format, jobs.get(i).name(), milliss[i], ratios[i]);
176 }
177
178 private static String keywordValue(String[] args, String keyword) {
179 for (String arg : args)
180 if (arg.startsWith(keyword))
181 return arg.substring(keyword.length() + 1);
182 return null;
183 }
184
185 private static int intArg(String[] args, String keyword, int defaultValue) {
186 String val = keywordValue(args, keyword);
187 return (val == null) ? defaultValue : Integer.parseInt(val);
188 }
189
190 private static double doubleArg(String[] args, String keyword, double defaultValue) {
191 String val = keywordValue(args, keyword);
192 return (val == null) ? defaultValue : Double.parseDouble(val);
193 }
194
195 private static Pattern patternArg(String[] args, String keyword) {
196 String val = keywordValue(args, keyword);
197 return (val == null) ? null : Pattern.compile(val);
198 }
199
200 private static boolean booleanArg(String[] args, String keyword) {
201 String val = keywordValue(args, keyword);
202 if (val == null || val.equals("false")) return false;
203 if (val.equals("true")) return true;
204 throw new IllegalArgumentException(val);
205 }
206
207 private static List<Job> filter(Pattern filter, List<Job> jobs) {
208 return (filter == null) ? jobs
209 : jobs.stream()
210 .filter(job -> filter.matcher(job.name()).find())
211 .collect(toList());
212 }
213
214 private static void deoptimize(int sum) {
215 if (sum == 42)
216 System.out.println("the answer");
217 }
218
219 private static <T> List<T> asSubList(List<T> list) {
220 return list.subList(0, list.size());
221 }
222
223 private static <T> Iterable<T> backwards(final List<T> list) {
224 return new Iterable<T>() {
225 public Iterator<T> iterator() {
226 return new Iterator<T>() {
227 final ListIterator<T> it = list.listIterator(list.size());
228 public boolean hasNext() { return it.hasPrevious(); }
229 public T next() { return it.previous(); }
230 public void remove() { it.remove(); }};}};
231 }
232
233 // Checks for correctness *and* prevents loop optimizations
234 static class Check {
235 private int sum;
236 public void sum(int sum) {
237 if (this.sum == 0)
238 this.sum = sum;
239 if (this.sum != sum)
240 throw new AssertionError("Sum mismatch");
241 }
242 }
243 volatile Check check = new Check();
244
245 public static void main(String[] args) throws Throwable {
246 new IteratorMicroBenchmark(args).run();
247 }
248
249 void run() throws Throwable {
250 // System.out.printf(
251 // "iterations=%d size=%d, warmup=%1g, filter=\"%s\"%n",
252 // iterations, size, warmupSeconds, filter);
253
254 final ArrayList<Integer> al = new ArrayList<>(size);
255
256 // Populate collections with random data
257 final ThreadLocalRandom rnd = ThreadLocalRandom.current();
258 for (int i = 0; i < size; i++)
259 al.add(rnd.nextInt(size));
260
261 final ArrayDeque<Integer> ad = new ArrayDeque<>(al);
262 final ArrayBlockingQueue<Integer> abq = new ArrayBlockingQueue<>(al.size());
263 abq.addAll(al);
264
265 // shuffle circular array elements so they wrap
266 for (int i = 0, n = rnd.nextInt(size); i < n; i++) {
267 ad.addLast(ad.removeFirst());
268 abq.add(abq.remove());
269 }
270
271 ArrayList<Job> jobs = new ArrayList<>();
272
273 List.<Collection<Integer>>of(
274 al, ad, abq,
275 new LinkedList<>(al),
276 new PriorityQueue<>(al),
277 new Vector<>(al),
278 new ConcurrentLinkedQueue<>(al),
279 new ConcurrentLinkedDeque<>(al),
280 new LinkedBlockingQueue<>(al),
281 new LinkedBlockingDeque<>(al),
282 new LinkedTransferQueue<>(al),
283 new PriorityBlockingQueue<>(al)).forEach(
284 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 if (x.removeIf(n -> { sum[0] += n; return false; }))
334 throw new AssertionError();
335 check.sum(sum[0]);}}},
336 new Job(klazz + " contains") {
337 public void work() throws Throwable {
338 int[] sum = new int[1];
339 Object y = new Object() {
340 public boolean equals(Object z) {
341 sum[0] += (int) z; return false; }};
342 for (int i = 0; i < iterations; i++) {
343 sum[0] = 0;
344 if (x.contains(y)) throw new AssertionError();
345 check.sum(sum[0]);}}},
346 new Job(klazz + " remove(Object)") {
347 public void work() throws Throwable {
348 int[] sum = new int[1];
349 Object y = new Object() {
350 public boolean equals(Object z) {
351 sum[0] += (int) z; return false; }};
352 for (int i = 0; i < iterations; i++) {
353 sum[0] = 0;
354 if (x.remove(y)) throw new AssertionError();
355 check.sum(sum[0]);}}},
356 new Job(klazz + " forEach") {
357 public void work() throws Throwable {
358 int[] sum = new int[1];
359 for (int i = 0; i < iterations; i++) {
360 sum[0] = 0;
361 x.forEach(n -> sum[0] += n);
362 check.sum(sum[0]);}}},
363 new Job(klazz + " toArray()") {
364 public void work() throws Throwable {
365 int[] sum = new int[1];
366 for (int i = 0; i < iterations; i++) {
367 sum[0] = 0;
368 for (Object o : x.toArray())
369 sum[0] += (Integer) o;
370 check.sum(sum[0]);}}},
371 new Job(klazz + " toArray(a)") {
372 public void work() throws Throwable {
373 Integer[] a = new Integer[x.size()];
374 int[] sum = new int[1];
375 for (int i = 0; i < iterations; i++) {
376 sum[0] = 0;
377 x.toArray(a);
378 for (Object o : a)
379 sum[0] += (Integer) o;
380 check.sum(sum[0]);}}},
381 new Job(klazz + " toArray(empty)") {
382 public void work() throws Throwable {
383 Integer[] empty = new Integer[0];
384 int[] sum = new int[1];
385 for (int i = 0; i < iterations; i++) {
386 sum[0] = 0;
387 for (Integer o : x.toArray(empty))
388 sum[0] += o;
389 check.sum(sum[0]);}}},
390 new Job(klazz + " stream().forEach") {
391 public void work() throws Throwable {
392 int[] sum = new int[1];
393 for (int i = 0; i < iterations; i++) {
394 sum[0] = 0;
395 x.stream().forEach(n -> sum[0] += n);
396 check.sum(sum[0]);}}},
397 new Job(klazz + " stream().mapToInt") {
398 public void work() throws Throwable {
399 for (int i = 0; i < iterations; i++) {
400 check.sum(x.stream().mapToInt(e -> e).sum());}}},
401 new Job(klazz + " stream().collect") {
402 public void work() throws Throwable {
403 for (int i = 0; i < iterations; i++) {
404 check.sum(x.stream()
405 .collect(summingInt(e -> e)));}}},
406 new Job(klazz + " stream()::iterator") {
407 public void work() throws Throwable {
408 int[] sum = new int[1];
409 for (int i = 0; i < iterations; i++) {
410 sum[0] = 0;
411 for (Integer o : (Iterable<Integer>) x.stream()::iterator)
412 sum[0] += o;
413 check.sum(sum[0]);}}},
414 new Job(klazz + " parallelStream().forEach") {
415 public void work() throws Throwable {
416 for (int i = 0; i < iterations; i++) {
417 LongAdder sum = new LongAdder();
418 x.parallelStream().forEach(n -> sum.add(n));
419 check.sum((int) sum.sum());}}},
420 new Job(klazz + " parallelStream().mapToInt") {
421 public void work() throws Throwable {
422 for (int i = 0; i < iterations; i++) {
423 check.sum(x.parallelStream().mapToInt(e -> e).sum());}}},
424 new Job(klazz + " parallelStream().collect") {
425 public void work() throws Throwable {
426 for (int i = 0; i < iterations; i++) {
427 check.sum(x.parallelStream()
428 .collect(summingInt(e -> e)));}}},
429 new Job(klazz + " parallelStream()::iterator") {
430 public void work() throws Throwable {
431 int[] sum = new int[1];
432 for (int i = 0; i < iterations; i++) {
433 sum[0] = 0;
434 for (Integer o : (Iterable<Integer>) x.parallelStream()::iterator)
435 sum[0] += o;
436 check.sum(sum[0]);}}});
437 }
438
439 List<Job> dequeJobs(Deque<Integer> x) {
440 String klazz = x.getClass().getSimpleName();
441 return List.of(
442 new Job(klazz + " descendingIterator() loop") {
443 public void work() throws Throwable {
444 for (int i = 0; i < iterations; i++) {
445 int sum = 0;
446 Iterator<Integer> it = x.descendingIterator();
447 while (it.hasNext())
448 sum += it.next();
449 check.sum(sum);}}},
450 new Job(klazz + " descendingIterator().forEachRemaining()") {
451 public void work() throws Throwable {
452 int[] sum = new int[1];
453 for (int i = 0; i < iterations; i++) {
454 sum[0] = 0;
455 x.descendingIterator().forEachRemaining(n -> sum[0] += n);
456 check.sum(sum[0]);}}});
457 }
458 }