ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/test/jtreg/util/Collection/IteratorMicroBenchmark.java
Revision: 1.12
Committed: Mon Nov 28 02:00:48 2016 UTC (7 years, 6 months ago) by jsr166
Branch: MAIN
Changes since 1.11: +13 -1 lines
Log Message:
add stream, parallelStream

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.Enumeration;
40     import java.util.Iterator;
41     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.ConcurrentSkipListMap;
55     import java.util.concurrent.CountDownLatch;
56     import java.util.concurrent.ThreadLocalRandom;
57     import java.util.concurrent.TimeUnit;
58     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     final ArrayList<Integer> al = new ArrayList<Integer>(size);
258    
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.8 new PriorityQueue<>(al),
278 jsr166 1.1 new Vector<>(al),
279     new ConcurrentLinkedQueue<>(al),
280     new ConcurrentLinkedDeque<>(al),
281     new LinkedBlockingQueue<>(al),
282     new LinkedBlockingDeque<>(al),
283 jsr166 1.8 new LinkedTransferQueue<>(al),
284     new PriorityBlockingQueue<>(al))
285 jsr166 1.1 .stream()
286     .forEach(x -> {
287     jobs.addAll(collectionJobs(x));
288     if (x instanceof Deque)
289     jobs.addAll(dequeJobs((Deque<Integer>)x));
290     });
291    
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.5 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.5 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.5 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.5 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     x.removeIf(n -> { sum[0] += n; return false; });
336     check.sum(sum[0]);}}},
337 jsr166 1.5 new Job(klazz + " .forEach") {
338 jsr166 1.1 public void work() throws Throwable {
339     int[] sum = new int[1];
340     for (int i = 0; i < iterations; i++) {
341     sum[0] = 0;
342     x.forEach(n -> sum[0] += n);
343 jsr166 1.6 check.sum(sum[0]);}}},
344     new Job(klazz + " .toArray()") {
345     public void work() throws Throwable {
346     int[] sum = new int[1];
347     for (int i = 0; i < iterations; i++) {
348     sum[0] = 0;
349     for (Object o : x.toArray())
350     sum[0] += (Integer) o;
351     check.sum(sum[0]);}}},
352     new Job(klazz + " .toArray(a)") {
353     public void work() throws Throwable {
354     Integer[] a = new Integer[x.size()];
355     int[] sum = new int[1];
356     for (int i = 0; i < iterations; i++) {
357     sum[0] = 0;
358     x.toArray(a);
359     for (Object o : a)
360     sum[0] += (Integer) o;
361 jsr166 1.7 check.sum(sum[0]);}}},
362     new Job(klazz + " .toArray(empty)") {
363     public void work() throws Throwable {
364     Integer[] empty = new Integer[0];
365     int[] sum = new int[1];
366     for (int i = 0; i < iterations; i++) {
367     sum[0] = 0;
368     for (Integer o : x.toArray(empty))
369     sum[0] += o;
370 jsr166 1.12 check.sum(sum[0]);}}},
371     new Job(klazz + " .stream().collect") {
372     public void work() throws Throwable {
373     for (int i = 0; i < iterations; i++) {
374     check.sum(x.stream()
375     .collect(summingInt(e -> e)));}}},
376     new Job(klazz + " .parallelStream().collect") {
377     public void work() throws Throwable {
378     for (int i = 0; i < iterations; i++) {
379     check.sum(x.parallelStream()
380     .collect(summingInt(e -> e)));}}});
381 jsr166 1.1 }
382    
383     List<Job> dequeJobs(Deque<Integer> x) {
384     String klazz = x.getClass().getSimpleName();
385     return List.of(
386 jsr166 1.5 new Job(klazz + " .descendingIterator() loop") {
387 jsr166 1.1 public void work() throws Throwable {
388     for (int i = 0; i < iterations; i++) {
389     int sum = 0;
390     Iterator<Integer> it = x.descendingIterator();
391     while (it.hasNext())
392     sum += it.next();
393     check.sum(sum);}}},
394 jsr166 1.5 new Job(klazz + " .descendingIterator().forEachRemaining()") {
395 jsr166 1.1 public void work() throws Throwable {
396     int[] sum = new int[1];
397     for (int i = 0; i < iterations; i++) {
398     sum[0] = 0;
399     x.descendingIterator().forEachRemaining(n -> sum[0] += n);
400     check.sum(sum[0]);}}});
401     }
402     }