ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/test/jtreg/util/Collection/IteratorMicroBenchmark.java
Revision: 1.25
Committed: Sun Oct 22 01:07:33 2017 UTC (6 years, 7 months ago) by jsr166
Branch: MAIN
Changes since 1.24: +1 -1 lines
Log Message:
take errorprone [ClassCanBeStatic] advice

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
32 import java.lang.ref.WeakReference;
33 import java.util.ArrayDeque;
34 import java.util.Arrays;
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 if (filter == null) return jobs;
209 ArrayList<Job> newJobs = new ArrayList<>();
210 for (Job job : jobs)
211 if (filter.matcher(job.name()).find())
212 newJobs.add(job);
213 return newJobs;
214 }
215
216 private static void deoptimize(int sum) {
217 if (sum == 42)
218 System.out.println("the answer");
219 }
220
221 private static <T> List<T> asSubList(List<T> list) {
222 return list.subList(0, list.size());
223 }
224
225 private static <T> Iterable<T> backwards(final List<T> list) {
226 return new Iterable<T>() {
227 public Iterator<T> iterator() {
228 return new Iterator<T>() {
229 final ListIterator<T> it = list.listIterator(list.size());
230 public boolean hasNext() { return it.hasPrevious(); }
231 public T next() { return it.previous(); }
232 public void remove() { it.remove(); }};}};
233 }
234
235 // Checks for correctness *and* prevents loop optimizations
236 static class Check {
237 private int sum;
238 public void sum(int sum) {
239 if (this.sum == 0)
240 this.sum = sum;
241 if (this.sum != sum)
242 throw new AssertionError("Sum mismatch");
243 }
244 }
245 volatile Check check = new Check();
246
247 public static void main(String[] args) throws Throwable {
248 new IteratorMicroBenchmark(args).run();
249 }
250
251 void run() throws Throwable {
252 // System.out.printf(
253 // "iterations=%d size=%d, warmup=%1g, filter=\"%s\"%n",
254 // iterations, size, warmupSeconds, filter);
255
256 final ArrayList<Integer> al = new ArrayList<>(size);
257
258 // Populate collections with random data
259 final ThreadLocalRandom rnd = ThreadLocalRandom.current();
260 for (int i = 0; i < size; i++)
261 al.add(rnd.nextInt(size));
262
263 final ArrayDeque<Integer> ad = new ArrayDeque<>(al);
264 final ArrayBlockingQueue<Integer> abq = new ArrayBlockingQueue<>(al.size());
265 abq.addAll(al);
266
267 // shuffle circular array elements so they wrap
268 for (int i = 0, n = rnd.nextInt(size); i < n; i++) {
269 ad.addLast(ad.removeFirst());
270 abq.add(abq.remove());
271 }
272
273 ArrayList<Job> jobs = new ArrayList<>(Arrays.asList());
274
275 List.of(al, ad, abq,
276 new LinkedList<>(al),
277 new PriorityQueue<>(al),
278 new Vector<>(al),
279 new ConcurrentLinkedQueue<>(al),
280 new ConcurrentLinkedDeque<>(al),
281 new LinkedBlockingQueue<>(al),
282 new LinkedBlockingDeque<>(al),
283 new LinkedTransferQueue<>(al),
284 new PriorityBlockingQueue<>(al))
285 .stream()
286 .forEach(x -> {
287 jobs.addAll(collectionJobs(x));
288 if (x instanceof Deque)
289 jobs.addAll(dequeJobs((Deque<Integer>)x));
290 });
291
292 if (reverse) Collections.reverse(jobs);
293 if (shuffle) Collections.shuffle(jobs);
294
295 time(filter(filter, jobs));
296 }
297
298 List<Job> collectionJobs(Collection<Integer> x) {
299 String klazz = x.getClass().getSimpleName();
300 return List.of(
301 new Job(klazz + " iterate for loop") {
302 public void work() throws Throwable {
303 for (int i = 0; i < iterations; i++) {
304 int sum = 0;
305 for (Integer n : x)
306 sum += n;
307 check.sum(sum);}}},
308 new Job(klazz + " iterator().forEachRemaining()") {
309 public void work() throws Throwable {
310 int[] sum = new int[1];
311 for (int i = 0; i < iterations; i++) {
312 sum[0] = 0;
313 x.iterator().forEachRemaining(n -> sum[0] += n);
314 check.sum(sum[0]);}}},
315 new Job(klazz + " spliterator().tryAdvance()") {
316 public void work() throws Throwable {
317 int[] sum = new int[1];
318 for (int i = 0; i < iterations; i++) {
319 sum[0] = 0;
320 Spliterator<Integer> spliterator = x.spliterator();
321 do {} while (spliterator.tryAdvance(n -> sum[0] += n));
322 check.sum(sum[0]);}}},
323 new Job(klazz + " spliterator().forEachRemaining()") {
324 public void work() throws Throwable {
325 int[] sum = new int[1];
326 for (int i = 0; i < iterations; i++) {
327 sum[0] = 0;
328 x.spliterator().forEachRemaining(n -> sum[0] += n);
329 check.sum(sum[0]);}}},
330 new Job(klazz + " removeIf") {
331 public void work() throws Throwable {
332 int[] sum = new int[1];
333 for (int i = 0; i < iterations; i++) {
334 sum[0] = 0;
335 if (x.removeIf(n -> { sum[0] += n; return false; }))
336 throw new AssertionError();
337 check.sum(sum[0]);}}},
338 new Job(klazz + " contains") {
339 public void work() throws Throwable {
340 int[] sum = new int[1];
341 Object y = new Object() {
342 public boolean equals(Object z) {
343 sum[0] += (int) z; return false; }};
344 for (int i = 0; i < iterations; i++) {
345 sum[0] = 0;
346 if (x.contains(y)) throw new AssertionError();
347 check.sum(sum[0]);}}},
348 new Job(klazz + " remove(Object)") {
349 public void work() throws Throwable {
350 int[] sum = new int[1];
351 Object y = new Object() {
352 public boolean equals(Object z) {
353 sum[0] += (int) z; return false; }};
354 for (int i = 0; i < iterations; i++) {
355 sum[0] = 0;
356 if (x.remove(y)) throw new AssertionError();
357 check.sum(sum[0]);}}},
358 new Job(klazz + " forEach") {
359 public void work() throws Throwable {
360 int[] sum = new int[1];
361 for (int i = 0; i < iterations; i++) {
362 sum[0] = 0;
363 x.forEach(n -> sum[0] += n);
364 check.sum(sum[0]);}}},
365 new Job(klazz + " toArray()") {
366 public void work() throws Throwable {
367 int[] sum = new int[1];
368 for (int i = 0; i < iterations; i++) {
369 sum[0] = 0;
370 for (Object o : x.toArray())
371 sum[0] += (Integer) o;
372 check.sum(sum[0]);}}},
373 new Job(klazz + " toArray(a)") {
374 public void work() throws Throwable {
375 Integer[] a = new Integer[x.size()];
376 int[] sum = new int[1];
377 for (int i = 0; i < iterations; i++) {
378 sum[0] = 0;
379 x.toArray(a);
380 for (Object o : a)
381 sum[0] += (Integer) o;
382 check.sum(sum[0]);}}},
383 new Job(klazz + " toArray(empty)") {
384 public void work() throws Throwable {
385 Integer[] empty = new Integer[0];
386 int[] sum = new int[1];
387 for (int i = 0; i < iterations; i++) {
388 sum[0] = 0;
389 for (Integer o : x.toArray(empty))
390 sum[0] += o;
391 check.sum(sum[0]);}}},
392 new Job(klazz + " stream().forEach") {
393 public void work() throws Throwable {
394 int[] sum = new int[1];
395 for (int i = 0; i < iterations; i++) {
396 sum[0] = 0;
397 x.stream().forEach(n -> sum[0] += n);
398 check.sum(sum[0]);}}},
399 new Job(klazz + " stream().mapToInt") {
400 public void work() throws Throwable {
401 for (int i = 0; i < iterations; i++) {
402 check.sum(x.stream().mapToInt(e -> e).sum());}}},
403 new Job(klazz + " stream().collect") {
404 public void work() throws Throwable {
405 for (int i = 0; i < iterations; i++) {
406 check.sum(x.stream()
407 .collect(summingInt(e -> e)));}}},
408 new Job(klazz + " stream()::iterator") {
409 public void work() throws Throwable {
410 int[] sum = new int[1];
411 for (int i = 0; i < iterations; i++) {
412 sum[0] = 0;
413 for (Integer o : (Iterable<Integer>) x.stream()::iterator)
414 sum[0] += o;
415 check.sum(sum[0]);}}},
416 new Job(klazz + " parallelStream().forEach") {
417 public void work() throws Throwable {
418 for (int i = 0; i < iterations; i++) {
419 LongAdder sum = new LongAdder();
420 x.parallelStream().forEach(n -> sum.add(n));
421 check.sum((int) sum.sum());}}},
422 new Job(klazz + " parallelStream().mapToInt") {
423 public void work() throws Throwable {
424 for (int i = 0; i < iterations; i++) {
425 check.sum(x.parallelStream().mapToInt(e -> e).sum());}}},
426 new Job(klazz + " parallelStream().collect") {
427 public void work() throws Throwable {
428 for (int i = 0; i < iterations; i++) {
429 check.sum(x.parallelStream()
430 .collect(summingInt(e -> e)));}}},
431 new Job(klazz + " parallelStream()::iterator") {
432 public void work() throws Throwable {
433 int[] sum = new int[1];
434 for (int i = 0; i < iterations; i++) {
435 sum[0] = 0;
436 for (Integer o : (Iterable<Integer>) x.parallelStream()::iterator)
437 sum[0] += o;
438 check.sum(sum[0]);}}});
439 }
440
441 List<Job> dequeJobs(Deque<Integer> x) {
442 String klazz = x.getClass().getSimpleName();
443 return List.of(
444 new Job(klazz + " descendingIterator() loop") {
445 public void work() throws Throwable {
446 for (int i = 0; i < iterations; i++) {
447 int sum = 0;
448 Iterator<Integer> it = x.descendingIterator();
449 while (it.hasNext())
450 sum += it.next();
451 check.sum(sum);}}},
452 new Job(klazz + " descendingIterator().forEachRemaining()") {
453 public void work() throws Throwable {
454 int[] sum = new int[1];
455 for (int i = 0; i < iterations; i++) {
456 sum[0] = 0;
457 x.descendingIterator().forEachRemaining(n -> sum[0] += n);
458 check.sum(sum[0]);}}});
459 }
460 }