ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/test/jtreg/util/Collection/IteratorMicroBenchmark.java
Revision: 1.27
Committed: Sun Jan 7 20:19:00 2018 UTC (6 years, 5 months ago) by jsr166
Branch: MAIN
Changes since 1.26: +16 -16 lines
Log Message:
simplify c.stream().forEach to c.forEach

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 jsr166 1.8 import java.util.PriorityQueue;
44 jsr166 1.1 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 jsr166 1.8 import java.util.concurrent.PriorityBlockingQueue;
53 jsr166 1.1 import java.util.concurrent.CountDownLatch;
54     import java.util.concurrent.ThreadLocalRandom;
55     import java.util.concurrent.TimeUnit;
56 jsr166 1.19 import java.util.concurrent.atomic.LongAdder;
57 jsr166 1.1 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 jsr166 1.11 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 jsr166 1.1
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 jsr166 1.9 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 jsr166 1.1 }
137     return nanoss;
138     }
139    
140     void time(List<Job> jobs) throws Throwable {
141 jsr166 1.9 if (warmupNanos > 0) time0(jobs); // Warm up run
142 jsr166 1.1 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 jsr166 1.10 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 jsr166 1.1 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 jsr166 1.25 static class Check {
237 jsr166 1.1 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 jsr166 1.2 volatile Check check = new Check();
246 jsr166 1.1
247     public static void main(String[] args) throws Throwable {
248 jsr166 1.11 new IteratorMicroBenchmark(args).run();
249 jsr166 1.1 }
250    
251 jsr166 1.11 void run() throws Throwable {
252 jsr166 1.1 // System.out.printf(
253     // "iterations=%d size=%d, warmup=%1g, filter=\"%s\"%n",
254     // iterations, size, warmupSeconds, filter);
255    
256 jsr166 1.17 final ArrayList<Integer> al = new ArrayList<>(size);
257 jsr166 1.1
258     // Populate collections with random data
259     final ThreadLocalRandom rnd = ThreadLocalRandom.current();
260 jsr166 1.3 for (int i = 0; i < size; i++)
261 jsr166 1.1 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 jsr166 1.26 ArrayList<Job> jobs = new ArrayList<>();
274 jsr166 1.1
275 jsr166 1.27 List.<Collection<Integer>>of(
276     al, ad, abq,
277     new LinkedList<>(al),
278     new PriorityQueue<>(al),
279     new Vector<>(al),
280     new ConcurrentLinkedQueue<>(al),
281     new ConcurrentLinkedDeque<>(al),
282     new LinkedBlockingQueue<>(al),
283     new LinkedBlockingDeque<>(al),
284     new LinkedTransferQueue<>(al),
285     new PriorityBlockingQueue<>(al)).forEach(
286     x -> {
287     jobs.addAll(collectionJobs(x));
288     if (x instanceof Deque)
289     jobs.addAll(dequeJobs((Deque<Integer>)x));
290     });
291 jsr166 1.1
292 jsr166 1.11 if (reverse) Collections.reverse(jobs);
293 jsr166 1.10 if (shuffle) Collections.shuffle(jobs);
294    
295 jsr166 1.1 time(filter(filter, jobs));
296     }
297    
298     List<Job> collectionJobs(Collection<Integer> x) {
299     String klazz = x.getClass().getSimpleName();
300     return List.of(
301 jsr166 1.5 new Job(klazz + " iterate for loop") {
302 jsr166 1.1 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 jsr166 1.18 new Job(klazz + " iterator().forEachRemaining()") {
309 jsr166 1.1 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 jsr166 1.18 new Job(klazz + " spliterator().tryAdvance()") {
316 jsr166 1.1 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 jsr166 1.18 new Job(klazz + " spliterator().forEachRemaining()") {
324 jsr166 1.1 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 jsr166 1.18 new Job(klazz + " removeIf") {
331 jsr166 1.1 public void work() throws Throwable {
332     int[] sum = new int[1];
333     for (int i = 0; i < iterations; i++) {
334     sum[0] = 0;
335 jsr166 1.16 if (x.removeIf(n -> { sum[0] += n; return false; }))
336     throw new AssertionError();
337 jsr166 1.1 check.sum(sum[0]);}}},
338 jsr166 1.18 new Job(klazz + " contains") {
339 jsr166 1.14 public void work() throws Throwable {
340     int[] sum = new int[1];
341 jsr166 1.15 Object y = new Object() {
342     public boolean equals(Object z) {
343     sum[0] += (int) z; return false; }};
344 jsr166 1.14 for (int i = 0; i < iterations; i++) {
345     sum[0] = 0;
346 jsr166 1.16 if (x.contains(y)) throw new AssertionError();
347     check.sum(sum[0]);}}},
348 jsr166 1.18 new Job(klazz + " remove(Object)") {
349 jsr166 1.16 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 jsr166 1.14 check.sum(sum[0]);}}},
358 jsr166 1.18 new Job(klazz + " forEach") {
359 jsr166 1.1 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 jsr166 1.6 check.sum(sum[0]);}}},
365 jsr166 1.18 new Job(klazz + " toArray()") {
366 jsr166 1.6 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 jsr166 1.18 new Job(klazz + " toArray(a)") {
374 jsr166 1.6 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 jsr166 1.7 check.sum(sum[0]);}}},
383 jsr166 1.18 new Job(klazz + " toArray(empty)") {
384 jsr166 1.7 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 jsr166 1.12 check.sum(sum[0]);}}},
392 jsr166 1.19 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 jsr166 1.18 new Job(klazz + " stream().collect") {
404 jsr166 1.12 public void work() throws Throwable {
405     for (int i = 0; i < iterations; i++) {
406     check.sum(x.stream()
407     .collect(summingInt(e -> e)));}}},
408 jsr166 1.21 new Job(klazz + " stream()::iterator") {
409 jsr166 1.20 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 jsr166 1.19 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 jsr166 1.18 new Job(klazz + " parallelStream().collect") {
427 jsr166 1.12 public void work() throws Throwable {
428     for (int i = 0; i < iterations; i++) {
429     check.sum(x.parallelStream()
430 jsr166 1.20 .collect(summingInt(e -> e)));}}},
431 jsr166 1.21 new Job(klazz + " parallelStream()::iterator") {
432 jsr166 1.20 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 jsr166 1.1 }
440    
441     List<Job> dequeJobs(Deque<Integer> x) {
442     String klazz = x.getClass().getSimpleName();
443     return List.of(
444 jsr166 1.18 new Job(klazz + " descendingIterator() loop") {
445 jsr166 1.1 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 jsr166 1.18 new Job(klazz + " descendingIterator().forEachRemaining()") {
453 jsr166 1.1 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     }