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 RemoveMicroBenchmark 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.LinkedList; |
39 |
import java.util.List; |
40 |
import java.util.ListIterator; |
41 |
import java.util.Map; |
42 |
import java.util.PriorityQueue; |
43 |
import java.util.Spliterator; |
44 |
import java.util.Vector; |
45 |
import java.util.concurrent.ArrayBlockingQueue; |
46 |
import java.util.concurrent.BlockingQueue; |
47 |
import java.util.concurrent.ConcurrentLinkedDeque; |
48 |
import java.util.concurrent.ConcurrentLinkedQueue; |
49 |
import java.util.concurrent.CountDownLatch; |
50 |
import java.util.concurrent.LinkedBlockingDeque; |
51 |
import java.util.concurrent.LinkedBlockingQueue; |
52 |
import java.util.concurrent.LinkedTransferQueue; |
53 |
import java.util.concurrent.PriorityBlockingQueue; |
54 |
import java.util.concurrent.ThreadLocalRandom; |
55 |
import java.util.concurrent.TimeUnit; |
56 |
import java.util.regex.Pattern; |
57 |
import java.util.function.Supplier; |
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 |
* @author Martin Buchholz |
67 |
*/ |
68 |
public class RemoveMicroBenchmark { |
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 RemoveMicroBenchmark().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", 5); |
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 |
ArrayList<Job> jobs = new ArrayList<>(); |
249 |
|
250 |
List.<Collection<Integer>>of( |
251 |
new ArrayList<>(), |
252 |
new LinkedList<>(), |
253 |
new Vector<>(), |
254 |
new ArrayDeque<>(), |
255 |
new PriorityQueue<>(), |
256 |
new ArrayBlockingQueue<>(al.size()), |
257 |
new ConcurrentLinkedQueue<>(), |
258 |
new ConcurrentLinkedDeque<>(), |
259 |
new LinkedBlockingQueue<>(), |
260 |
new LinkedBlockingDeque<>(), |
261 |
new LinkedTransferQueue<>(), |
262 |
new PriorityBlockingQueue<>()) |
263 |
.stream().forEach( |
264 |
x -> { |
265 |
String klazz = x.getClass().getSimpleName(); |
266 |
jobs.addAll(collectionJobs(klazz, () -> x, al)); |
267 |
if (x instanceof Deque) { |
268 |
Deque<Integer> deque = (Deque<Integer>) x; |
269 |
jobs.addAll(dequeJobs(klazz, () -> deque, al)); |
270 |
} |
271 |
if (x instanceof BlockingQueue) { |
272 |
BlockingQueue<Integer> q = (BlockingQueue<Integer>) x; |
273 |
jobs.addAll(blockingQueueJobs(klazz, () -> q, al)); |
274 |
} |
275 |
if (x instanceof List) { |
276 |
List<Integer> list = (List<Integer>) x; |
277 |
jobs.addAll( |
278 |
collectionJobs( |
279 |
klazz + " subList", |
280 |
() -> list.subList(0, x.size()), |
281 |
al)); |
282 |
} |
283 |
}); |
284 |
|
285 |
time(filter(filter, jobs)); |
286 |
} |
287 |
|
288 |
Collection<Integer> universeRecorder(int[] sum) { |
289 |
return new ArrayList<>() { |
290 |
public boolean contains(Object x) { |
291 |
sum[0] += (Integer) x; |
292 |
return true; |
293 |
}}; |
294 |
} |
295 |
|
296 |
Collection<Integer> emptyRecorder(int[] sum) { |
297 |
return new ArrayList<>() { |
298 |
public boolean contains(Object x) { |
299 |
sum[0] += (Integer) x; |
300 |
return false; |
301 |
}}; |
302 |
} |
303 |
|
304 |
List<Job> collectionJobs( |
305 |
String description, |
306 |
Supplier<Collection<Integer>> supplier, |
307 |
ArrayList<Integer> al) { |
308 |
return List.of( |
309 |
new Job(description + " .removeIf") { |
310 |
public void work() throws Throwable { |
311 |
Collection<Integer> x = supplier.get(); |
312 |
int[] sum = new int[1]; |
313 |
for (int i = 0; i < iterations; i++) { |
314 |
sum[0] = 0; |
315 |
x.addAll(al); |
316 |
x.removeIf(n -> { sum[0] += n; return true; }); |
317 |
check.sum(sum[0]);}}}, |
318 |
new Job(description + " .removeAll") { |
319 |
public void work() throws Throwable { |
320 |
Collection<Integer> x = supplier.get(); |
321 |
int[] sum = new int[1]; |
322 |
Collection<Integer> universe = universeRecorder(sum); |
323 |
for (int i = 0; i < iterations; i++) { |
324 |
sum[0] = 0; |
325 |
x.addAll(al); |
326 |
x.removeAll(universe); |
327 |
check.sum(sum[0]);}}}, |
328 |
new Job(description + " .retainAll") { |
329 |
public void work() throws Throwable { |
330 |
Collection<Integer> x = supplier.get(); |
331 |
int[] sum = new int[1]; |
332 |
Collection<Integer> empty = emptyRecorder(sum); |
333 |
for (int i = 0; i < iterations; i++) { |
334 |
sum[0] = 0; |
335 |
x.addAll(al); |
336 |
x.retainAll(empty); |
337 |
check.sum(sum[0]);}}}, |
338 |
new Job(description + " Iterator.remove") { |
339 |
public void work() throws Throwable { |
340 |
Collection<Integer> x = supplier.get(); |
341 |
int[] sum = new int[1]; |
342 |
for (int i = 0; i < iterations; i++) { |
343 |
sum[0] = 0; |
344 |
x.addAll(al); |
345 |
Iterator<Integer> it = x.iterator(); |
346 |
while (it.hasNext()) { |
347 |
sum[0] += it.next(); |
348 |
it.remove(); |
349 |
} |
350 |
check.sum(sum[0]);}}}, |
351 |
new Job(description + " clear") { |
352 |
public void work() throws Throwable { |
353 |
Collection<Integer> x = supplier.get(); |
354 |
int[] sum = new int[1]; |
355 |
for (int i = 0; i < iterations; i++) { |
356 |
sum[0] = 0; |
357 |
x.addAll(al); |
358 |
x.forEach(e -> sum[0] += e); |
359 |
x.clear(); |
360 |
check.sum(sum[0]);}}}); |
361 |
} |
362 |
|
363 |
List<Job> dequeJobs( |
364 |
String description, |
365 |
Supplier<Deque<Integer>> supplier, |
366 |
ArrayList<Integer> al) { |
367 |
return List.of( |
368 |
new Job(description + " descendingIterator().remove") { |
369 |
public void work() throws Throwable { |
370 |
Deque<Integer> x = supplier.get(); |
371 |
int[] sum = new int[1]; |
372 |
for (int i = 0; i < iterations; i++) { |
373 |
sum[0] = 0; |
374 |
x.addAll(al); |
375 |
Iterator<Integer> it = x.descendingIterator(); |
376 |
while (it.hasNext()) { |
377 |
sum[0] += it.next(); |
378 |
it.remove(); |
379 |
} |
380 |
check.sum(sum[0]);}}}); |
381 |
} |
382 |
|
383 |
List<Job> blockingQueueJobs( |
384 |
String description, |
385 |
Supplier<BlockingQueue<Integer>> supplier, |
386 |
ArrayList<Integer> al) { |
387 |
return List.of( |
388 |
new Job(description + " drainTo(sink)") { |
389 |
public void work() throws Throwable { |
390 |
BlockingQueue<Integer> x = supplier.get(); |
391 |
ArrayList<Integer> sink = new ArrayList<>(); |
392 |
int[] sum = new int[1]; |
393 |
for (int i = 0; i < iterations; i++) { |
394 |
sum[0] = 0; |
395 |
sink.clear(); |
396 |
x.addAll(al); |
397 |
x.drainTo(sink); |
398 |
sink.forEach(e -> sum[0] += e); |
399 |
check.sum(sum[0]);}}}, |
400 |
new Job(description + " drainTo(sink, n)") { |
401 |
public void work() throws Throwable { |
402 |
BlockingQueue<Integer> x = supplier.get(); |
403 |
ArrayList<Integer> sink = new ArrayList<>(); |
404 |
int[] sum = new int[1]; |
405 |
for (int i = 0; i < iterations; i++) { |
406 |
sum[0] = 0; |
407 |
sink.clear(); |
408 |
x.addAll(al); |
409 |
x.drainTo(sink, al.size()); |
410 |
sink.forEach(e -> sum[0] += e); |
411 |
check.sum(sum[0]);}}}); |
412 |
} |
413 |
} |