ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/test/jtreg/util/Collection/IteratorMicroBenchmark.java
Revision: 1.23
Committed: Thu Sep 28 02:15:44 2017 UTC (6 years, 8 months ago) by jsr166
Branch: MAIN
Changes since 1.22: +0 -1 lines
Log Message:
removed unused imports

File Contents

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