ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/test/jtreg/util/Collection/IteratorMicroBenchmark.java
Revision: 1.9
Committed: Thu Nov 24 19:14:50 2016 UTC (7 years, 6 months ago) by jsr166
Branch: MAIN
Changes since 1.8: +13 -9 lines
Log Message:
small improvements

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