Path: blob/master/test/jdk/java/util/Collection/IteratorMicroBenchmark.java
41149 views
/*1* Copyright (c) 2007, Oracle and/or its affiliates. All rights reserved.2* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.3*4* This code is free software; you can redistribute it and/or modify it5* under the terms of the GNU General Public License version 2 only, as6* published by the Free Software Foundation.7*8* This code is distributed in the hope that it will be useful, but WITHOUT9* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or10* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License11* version 2 for more details (a copy is included in the LICENSE file that12* accompanied this code).13*14* You should have received a copy of the GNU General Public License version15* 2 along with this work; if not, write to the Free Software Foundation,16* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.17*18* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA19* or visit www.oracle.com if you need additional information or have any20* questions.21*/2223/*24* @test25* @summary micro-benchmark correctness mode26* @run main IteratorMicroBenchmark iterations=1 size=8 warmup=027*/2829import static java.util.concurrent.TimeUnit.MILLISECONDS;30import static java.util.stream.Collectors.summingInt;31import static java.util.stream.Collectors.toCollection;3233import java.lang.ref.ReferenceQueue;34import java.lang.ref.WeakReference;35import java.util.ArrayDeque;36import java.util.Arrays;37import java.util.ArrayList;38import java.util.Collection;39import java.util.Collections;40import java.util.Deque;41import java.util.HashMap;42import java.util.Iterator;43import java.util.LinkedList;44import java.util.List;45import java.util.ListIterator;46import java.util.PriorityQueue;47import java.util.Spliterator;48import java.util.Vector;49import java.util.concurrent.ArrayBlockingQueue;50import java.util.concurrent.ConcurrentLinkedDeque;51import java.util.concurrent.ConcurrentLinkedQueue;52import java.util.concurrent.CopyOnWriteArrayList;53import java.util.concurrent.LinkedBlockingDeque;54import java.util.concurrent.LinkedBlockingQueue;55import java.util.concurrent.LinkedTransferQueue;56import java.util.concurrent.PriorityBlockingQueue;57import java.util.concurrent.CountDownLatch;58import java.util.concurrent.ThreadLocalRandom;59import java.util.concurrent.atomic.LongAdder;60import java.util.function.UnaryOperator;61import java.util.regex.Pattern;62import java.util.stream.Stream;6364/**65* Usage: [iterations=N] [size=N] [filter=REGEXP] [warmup=SECONDS]66*67* To run this in micro-benchmark mode, simply run as a normal java program.68* Be patient; this program runs for a very long time.69* For faster runs, restrict execution using command line args.70*71* @author Martin Buchholz72*/73public class IteratorMicroBenchmark {74abstract static class Job {75private final String name;76public Job(String name) { this.name = name; }77public String name() { return name; }78public abstract void work() throws Throwable;79public void run() {80try { work(); }81catch (Throwable ex) {82// current job cannot always be deduced from stacktrace.83throw new RuntimeException("Job failed: " + name(), ex);84}85}86}8788final int iterations;89final int size; // number of elements in collections90final double warmupSeconds;91final long warmupNanos;92final Pattern nameFilter; // select subset of Jobs to run93final boolean reverse; // reverse order of Jobs94final boolean shuffle; // randomize order of Jobs9596IteratorMicroBenchmark(String[] args) {97iterations = intArg(args, "iterations", 10_000);98size = intArg(args, "size", 1000);99warmupSeconds = doubleArg(args, "warmup", 7.0);100nameFilter = patternArg(args, "filter");101reverse = booleanArg(args, "reverse");102shuffle = booleanArg(args, "shuffle");103104warmupNanos = (long) (warmupSeconds * (1000L * 1000L * 1000L));105}106107// --------------- GC finalization infrastructure ---------------108109/** No guarantees, but effective in practice. */110static void forceFullGc() {111long timeoutMillis = 1000L;112CountDownLatch finalized = new CountDownLatch(1);113ReferenceQueue<Object> queue = new ReferenceQueue<>();114WeakReference<Object> ref = new WeakReference<>(115new Object() {116@SuppressWarnings("deprecation")117protected void finalize() { finalized.countDown(); }},118queue);119try {120for (int tries = 3; tries--> 0; ) {121System.gc();122if (finalized.await(timeoutMillis, MILLISECONDS)123&& queue.remove(timeoutMillis) != null124&& ref.get() == null) {125System.runFinalization(); // try to pick up stragglers126return;127}128timeoutMillis *= 4;129}130} catch (InterruptedException unexpected) {131throw new AssertionError("unexpected InterruptedException");132}133throw new AssertionError("failed to do a \"full\" gc");134}135136/**137* Runs each job for long enough that all the runtime compilers138* have had plenty of time to warm up, i.e. get around to139* compiling everything worth compiling.140* Returns array of average times per job per run.141*/142long[] time0(List<Job> jobs) {143final int size = jobs.size();144long[] nanoss = new long[size];145for (int i = 0; i < size; i++) {146if (warmupNanos > 0) forceFullGc();147Job job = jobs.get(i);148long totalTime;149int runs = 0;150long startTime = System.nanoTime();151do { job.run(); runs++; }152while ((totalTime = System.nanoTime() - startTime) < warmupNanos);153nanoss[i] = totalTime/runs;154}155return nanoss;156}157158void time(List<Job> jobs) throws Throwable {159if (warmupNanos > 0) time0(jobs); // Warm up run160final int size = jobs.size();161final long[] nanoss = time0(jobs); // Real timing run162final long[] milliss = new long[size];163final double[] ratios = new double[size];164165final String nameHeader = "Method";166final String millisHeader = "Millis";167final String ratioHeader = "Ratio";168169int nameWidth = nameHeader.length();170int millisWidth = millisHeader.length();171int ratioWidth = ratioHeader.length();172173for (int i = 0; i < size; i++) {174nameWidth = Math.max(nameWidth, jobs.get(i).name().length());175176milliss[i] = nanoss[i]/(1000L * 1000L);177millisWidth = Math.max(millisWidth,178String.format("%d", milliss[i]).length());179180ratios[i] = (double) nanoss[i] / (double) nanoss[0];181ratioWidth = Math.max(ratioWidth,182String.format("%.3f", ratios[i]).length());183}184185String format = String.format("%%-%ds %%%dd %%%d.3f%%n",186nameWidth, millisWidth, ratioWidth);187String headerFormat = String.format("%%-%ds %%%ds %%%ds%%n",188nameWidth, millisWidth, ratioWidth);189System.out.printf(headerFormat, "Method", "Millis", "Ratio");190191// Print out absolute and relative times, calibrated against first job192for (int i = 0; i < size; i++)193System.out.printf(format, jobs.get(i).name(), milliss[i], ratios[i]);194}195196private static String keywordValue(String[] args, String keyword) {197for (String arg : args)198if (arg.startsWith(keyword))199return arg.substring(keyword.length() + 1);200return null;201}202203private static int intArg(String[] args, String keyword, int defaultValue) {204String val = keywordValue(args, keyword);205return (val == null) ? defaultValue : Integer.parseInt(val);206}207208private static double doubleArg(String[] args, String keyword, double defaultValue) {209String val = keywordValue(args, keyword);210return (val == null) ? defaultValue : Double.parseDouble(val);211}212213private static Pattern patternArg(String[] args, String keyword) {214String val = keywordValue(args, keyword);215return (val == null) ? null : Pattern.compile(val);216}217218private static boolean booleanArg(String[] args, String keyword) {219String val = keywordValue(args, keyword);220if (val == null || val.equals("false")) return false;221if (val.equals("true")) return true;222throw new IllegalArgumentException(val);223}224225private static void deoptimize(int sum) {226if (sum == 42)227System.out.println("the answer");228}229230private static <T> Iterable<T> backwards(final List<T> list) {231return new Iterable<T>() {232public Iterator<T> iterator() {233return new Iterator<T>() {234final ListIterator<T> it = list.listIterator(list.size());235public boolean hasNext() { return it.hasPrevious(); }236public T next() { return it.previous(); }237public void remove() { it.remove(); }};}};238}239240// Checks for correctness *and* prevents loop optimizations241static class Check {242private int sum;243public void sum(int sum) {244if (this.sum == 0)245this.sum = sum;246if (this.sum != sum)247throw new AssertionError("Sum mismatch");248}249}250volatile Check check = new Check();251252public static void main(String[] args) throws Throwable {253new IteratorMicroBenchmark(args).run();254}255256HashMap<Class<?>, String> goodClassName = new HashMap<>();257258String goodClassName(Class<?> klazz) {259return goodClassName.computeIfAbsent(260klazz,261k -> {262String simple = k.getSimpleName();263return (simple.equals("SubList")) // too simple!264? k.getName().replaceFirst(".*\\.", "")265: simple;266});267}268269String goodClassName(Object x) {270return goodClassName(x.getClass());271}272273static List<Integer> makeSubList(274List<Integer> elements,275UnaryOperator<List<Integer>> copyConstructor) {276final ArrayList<Integer> padded = new ArrayList<>();277final ThreadLocalRandom rnd = ThreadLocalRandom.current();278final int frontPorch = rnd.nextInt(3);279final int backPorch = rnd.nextInt(3);280for (int n = frontPorch; n--> 0; ) padded.add(rnd.nextInt());281padded.addAll(elements);282for (int n = backPorch; n--> 0; ) padded.add(rnd.nextInt());283return copyConstructor.apply(padded)284.subList(frontPorch, frontPorch + elements.size());285}286287void run() throws Throwable {288final ArrayList<Integer> al = new ArrayList<>(size);289290// Populate collections with random data291final ThreadLocalRandom rnd = ThreadLocalRandom.current();292for (int i = 0; i < size; i++)293al.add(rnd.nextInt(size));294295final ArrayDeque<Integer> ad = new ArrayDeque<>(al);296final ArrayBlockingQueue<Integer> abq = new ArrayBlockingQueue<>(al.size());297abq.addAll(al);298299// shuffle circular array elements so they wrap300for (int i = 0, n = rnd.nextInt(size); i < n; i++) {301ad.addLast(ad.removeFirst());302abq.add(abq.remove());303}304305final Integer[] array = al.toArray(new Integer[0]);306final List<Integer> immutableSubList307= makeSubList(al, x -> List.of(x.toArray(new Integer[0])));308309Stream<Collection<Integer>> collections = concatStreams(310Stream.of(311// Lists and their subLists312al,313makeSubList(al, ArrayList::new),314new Vector<>(al),315makeSubList(al, Vector::new),316new LinkedList<>(al),317makeSubList(al, LinkedList::new),318new CopyOnWriteArrayList<>(al),319makeSubList(al, CopyOnWriteArrayList::new),320321ad,322new PriorityQueue<>(al),323new ConcurrentLinkedQueue<>(al),324new ConcurrentLinkedDeque<>(al),325326// Blocking Queues327abq,328new LinkedBlockingQueue<>(al),329new LinkedBlockingDeque<>(al),330new LinkedTransferQueue<>(al),331new PriorityBlockingQueue<>(al),332333List.of(al.toArray(new Integer[0]))),334335// avoid UnsupportedOperationException in jdk9 and jdk10336(goodClassName(immutableSubList).equals("RandomAccessSubList"))337? Stream.empty()338: Stream.of(immutableSubList));339340ArrayList<Job> jobs = collections341.flatMap(x -> jobs(x))342.filter(job ->343nameFilter == null || nameFilter.matcher(job.name()).find())344.collect(toCollection(ArrayList::new));345346if (reverse) Collections.reverse(jobs);347if (shuffle) Collections.shuffle(jobs);348349time(jobs);350}351352@SafeVarargs @SuppressWarnings("varargs")353private static <T> Stream<T> concatStreams(Stream<T> ... streams) {354return Stream.of(streams).flatMap(s -> s);355}356357boolean isMutable(Collection<Integer> x) {358return !(x.getClass().getName().contains("ImmutableCollections$"));359}360361Stream<Job> jobs(Collection<Integer> x) {362return concatStreams(363collectionJobs(x),364365(isMutable(x))366? mutableCollectionJobs(x)367: Stream.empty(),368369(x instanceof Deque)370? dequeJobs((Deque<Integer>)x)371: Stream.empty(),372373(x instanceof List)374? listJobs((List<Integer>)x)375: Stream.empty(),376377(x instanceof List && isMutable(x))378? mutableListJobs((List<Integer>)x)379: Stream.empty());380}381382Object sneakyAdder(int[] sneakySum) {383return new Object() {384public int hashCode() { throw new AssertionError(); }385public boolean equals(Object z) {386sneakySum[0] += (int) z; return false; }};387}388389Stream<Job> collectionJobs(Collection<Integer> x) {390final String klazz = goodClassName(x);391return Stream.of(392new Job(klazz + " iterate for loop") {393public void work() throws Throwable {394for (int i = 0; i < iterations; i++) {395int sum = 0;396for (Integer n : x)397sum += n;398check.sum(sum);}}},399new Job(klazz + " iterator().forEachRemaining()") {400public void work() throws Throwable {401int[] sum = new int[1];402for (int i = 0; i < iterations; i++) {403sum[0] = 0;404x.iterator().forEachRemaining(n -> sum[0] += n);405check.sum(sum[0]);}}},406new Job(klazz + " spliterator().tryAdvance()") {407public void work() throws Throwable {408int[] sum = new int[1];409for (int i = 0; i < iterations; i++) {410sum[0] = 0;411Spliterator<Integer> spliterator = x.spliterator();412do {} while (spliterator.tryAdvance(n -> sum[0] += n));413check.sum(sum[0]);}}},414new Job(klazz + " spliterator().forEachRemaining()") {415public void work() throws Throwable {416int[] sum = new int[1];417for (int i = 0; i < iterations; i++) {418sum[0] = 0;419x.spliterator().forEachRemaining(n -> sum[0] += n);420check.sum(sum[0]);}}},421new Job(klazz + " contains") {422public void work() throws Throwable {423int[] sum = new int[1];424Object sneakyAdder = sneakyAdder(sum);425for (int i = 0; i < iterations; i++) {426sum[0] = 0;427if (x.contains(sneakyAdder)) throw new AssertionError();428check.sum(sum[0]);}}},429new Job(klazz + " containsAll") {430public void work() throws Throwable {431int[] sum = new int[1];432Collection<Object> sneakyAdderCollection =433Collections.singleton(sneakyAdder(sum));434for (int i = 0; i < iterations; i++) {435sum[0] = 0;436if (x.containsAll(sneakyAdderCollection))437throw new AssertionError();438check.sum(sum[0]);}}},439new Job(klazz + " forEach") {440public void work() throws Throwable {441int[] sum = new int[1];442for (int i = 0; i < iterations; i++) {443sum[0] = 0;444x.forEach(n -> sum[0] += n);445check.sum(sum[0]);}}},446new Job(klazz + " toArray()") {447public void work() throws Throwable {448int[] sum = new int[1];449for (int i = 0; i < iterations; i++) {450sum[0] = 0;451for (Object o : x.toArray())452sum[0] += (Integer) o;453check.sum(sum[0]);}}},454new Job(klazz + " toArray(a)") {455public void work() throws Throwable {456Integer[] a = new Integer[x.size()];457int[] sum = new int[1];458for (int i = 0; i < iterations; i++) {459sum[0] = 0;460x.toArray(a);461for (Object o : a)462sum[0] += (Integer) o;463check.sum(sum[0]);}}},464new Job(klazz + " toArray(empty)") {465public void work() throws Throwable {466Integer[] empty = new Integer[0];467int[] sum = new int[1];468for (int i = 0; i < iterations; i++) {469sum[0] = 0;470for (Integer o : x.toArray(empty))471sum[0] += o;472check.sum(sum[0]);}}},473new Job(klazz + " stream().forEach") {474public void work() throws Throwable {475int[] sum = new int[1];476for (int i = 0; i < iterations; i++) {477sum[0] = 0;478x.stream().forEach(n -> sum[0] += n);479check.sum(sum[0]);}}},480new Job(klazz + " stream().mapToInt") {481public void work() throws Throwable {482for (int i = 0; i < iterations; i++) {483check.sum(x.stream().mapToInt(e -> e).sum());}}},484new Job(klazz + " stream().collect") {485public void work() throws Throwable {486for (int i = 0; i < iterations; i++) {487check.sum(x.stream()488.collect(summingInt(e -> e)));}}},489new Job(klazz + " stream()::iterator") {490public void work() throws Throwable {491int[] sum = new int[1];492for (int i = 0; i < iterations; i++) {493sum[0] = 0;494for (Integer o : (Iterable<Integer>) x.stream()::iterator)495sum[0] += o;496check.sum(sum[0]);}}},497new Job(klazz + " parallelStream().forEach") {498public void work() throws Throwable {499for (int i = 0; i < iterations; i++) {500LongAdder sum = new LongAdder();501x.parallelStream().forEach(n -> sum.add(n));502check.sum((int) sum.sum());}}},503new Job(klazz + " parallelStream().mapToInt") {504public void work() throws Throwable {505for (int i = 0; i < iterations; i++) {506check.sum(x.parallelStream().mapToInt(e -> e).sum());}}},507new Job(klazz + " parallelStream().collect") {508public void work() throws Throwable {509for (int i = 0; i < iterations; i++) {510check.sum(x.parallelStream()511.collect(summingInt(e -> e)));}}},512new Job(klazz + " parallelStream()::iterator") {513public void work() throws Throwable {514int[] sum = new int[1];515for (int i = 0; i < iterations; i++) {516sum[0] = 0;517for (Integer o : (Iterable<Integer>) x.parallelStream()::iterator)518sum[0] += o;519check.sum(sum[0]);}}});520}521522Stream<Job> mutableCollectionJobs(Collection<Integer> x) {523final String klazz = goodClassName(x);524return Stream.of(525new Job(klazz + " removeIf") {526public void work() throws Throwable {527int[] sum = new int[1];528for (int i = 0; i < iterations; i++) {529sum[0] = 0;530if (x.removeIf(n -> { sum[0] += n; return false; }))531throw new AssertionError();532check.sum(sum[0]);}}},533new Job(klazz + " remove(Object)") {534public void work() throws Throwable {535int[] sum = new int[1];536Object sneakyAdder = sneakyAdder(sum);537for (int i = 0; i < iterations; i++) {538sum[0] = 0;539if (x.remove(sneakyAdder)) throw new AssertionError();540check.sum(sum[0]);}}});541}542543Stream<Job> dequeJobs(Deque<Integer> x) {544final String klazz = goodClassName(x);545return Stream.of(546new Job(klazz + " descendingIterator() loop") {547public void work() throws Throwable {548for (int i = 0; i < iterations; i++) {549int sum = 0;550Iterator<Integer> it = x.descendingIterator();551while (it.hasNext())552sum += it.next();553check.sum(sum);}}},554new Job(klazz + " descendingIterator().forEachRemaining()") {555public void work() throws Throwable {556int[] sum = new int[1];557for (int i = 0; i < iterations; i++) {558sum[0] = 0;559x.descendingIterator().forEachRemaining(n -> sum[0] += n);560check.sum(sum[0]);}}});561}562563Stream<Job> listJobs(List<Integer> x) {564final String klazz = goodClassName(x);565return Stream.of(566new Job(klazz + " listIterator forward loop") {567public void work() throws Throwable {568for (int i = 0; i < iterations; i++) {569int sum = 0;570ListIterator<Integer> it = x.listIterator();571while (it.hasNext())572sum += it.next();573check.sum(sum);}}},574new Job(klazz + " listIterator backward loop") {575public void work() throws Throwable {576for (int i = 0; i < iterations; i++) {577int sum = 0;578ListIterator<Integer> it = x.listIterator(x.size());579while (it.hasPrevious())580sum += it.previous();581check.sum(sum);}}},582new Job(klazz + " indexOf") {583public void work() throws Throwable {584int[] sum = new int[1];585Object sneakyAdder = sneakyAdder(sum);586for (int i = 0; i < iterations; i++) {587sum[0] = 0;588if (x.indexOf(sneakyAdder) != -1)589throw new AssertionError();590check.sum(sum[0]);}}},591new Job(klazz + " lastIndexOf") {592public void work() throws Throwable {593int[] sum = new int[1];594Object sneakyAdder = sneakyAdder(sum);595for (int i = 0; i < iterations; i++) {596sum[0] = 0;597if (x.lastIndexOf(sneakyAdder) != -1)598throw new AssertionError();599check.sum(sum[0]);}}},600new Job(klazz + " equals") {601public void work() throws Throwable {602ArrayList<Integer> copy = new ArrayList<>(x);603for (int i = 0; i < iterations; i++) {604if (!x.equals(copy))605throw new AssertionError();}}},606new Job(klazz + " hashCode") {607public void work() throws Throwable {608int hashCode = Arrays.hashCode(x.toArray());609for (int i = 0; i < iterations; i++) {610if (x.hashCode() != hashCode)611throw new AssertionError();}}});612}613614Stream<Job> mutableListJobs(List<Integer> x) {615final String klazz = goodClassName(x);616return Stream.of(617new Job(klazz + " replaceAll") {618public void work() throws Throwable {619int[] sum = new int[1];620UnaryOperator<Integer> sneakyAdder =621x -> { sum[0] += x; return x; };622for (int i = 0; i < iterations; i++) {623sum[0] = 0;624x.replaceAll(sneakyAdder);625check.sum(sum[0]);}}});626}627}628629630