repo
stringlengths
1
191
file
stringlengths
23
351
code
stringlengths
0
5.32M
file_length
int64
0
5.32M
avg_line_length
float64
0
2.9k
max_line_length
int64
0
288k
extension_type
stringclasses
1 value
jmh
jmh-master/jmh-core/src/main/java/org/openjdk/jmh/generators/core/HelperType.java
/* * Copyright (c) 2005, 2014, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package org.openjdk.jmh.generators.core; enum HelperType { SETUP, TEARDOWN, }
1,300
40.967742
79
java
jmh
jmh-master/jmh-core/src/main/java/org/openjdk/jmh/generators/core/Identifiers.java
/* * Copyright (c) 2005, 2014, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package org.openjdk.jmh.generators.core; import org.openjdk.jmh.annotations.Scope; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Set; class Identifiers { private final Map<String, String> collapsedTypes = new HashMap<>(); private int collapsedIndex = 0; private final Set<String> claimedJmhTypes = new HashSet<>(); private final Map<String, String> jmhTypes = new HashMap<>(); public String getJMHtype(ClassInfo type) { String id = BenchmarkGeneratorUtils.getGeneratedName(type); String jmhType = jmhTypes.get(id); if (jmhType == null) { int v = 0; do { jmhType = id + (v == 0 ? "" : "_" + v) + "_jmhType"; v++; } while (!claimedJmhTypes.add(jmhType)); jmhTypes.put(id, jmhType); } return jmhType; } public String collapseTypeName(String e) { if (collapsedTypes.containsKey(e)) { return collapsedTypes.get(e); } String[] strings = e.split("\\."); String name = strings[strings.length - 1].toLowerCase(); String collapsedName = name + (collapsedIndex++) + "_"; collapsedTypes.put(e, collapsedName); return collapsedName; } private int index = 0; public String identifier(Scope scope) { switch (scope) { case Benchmark: case Group: { return "G"; } case Thread: { return String.valueOf(index++); } default: throw new GenerationException("Unknown scope: " + scope, null); } } }
2,912
32.872093
79
java
jmh
jmh-master/jmh-core/src/main/java/org/openjdk/jmh/generators/core/MetadataInfo.java
/* * Copyright (c) 2005, 2014, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package org.openjdk.jmh.generators.core; /** * Super-interface for all metadata elements. */ public interface MetadataInfo { }
1,343
41
79
java
jmh
jmh-master/jmh-core/src/main/java/org/openjdk/jmh/generators/core/MethodGroup.java
/* * Copyright (c) 2005, 2022, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package org.openjdk.jmh.generators.core; import org.openjdk.jmh.annotations.*; import org.openjdk.jmh.runner.options.TimeValue; import org.openjdk.jmh.util.Optional; import java.lang.annotation.Annotation; import java.util.*; import java.util.concurrent.TimeUnit; class MethodGroup implements Comparable<MethodGroup> { private final ClassInfo ci; private final String name; private final Set<MethodInvocation> methods; private final EnumSet<Mode> modes; private final Map<String, String[]> params; private boolean strictFP; public MethodGroup(ClassInfo ci, String name) { this.ci = ci; this.name = name; this.methods = new TreeSet<>(); this.modes = EnumSet.noneOf(Mode.class); this.params = new TreeMap<>(); } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; MethodGroup methodGroup = (MethodGroup) o; if (!name.equals(methodGroup.name)) return false; return true; } @Override public int hashCode() { return name.hashCode(); } @Override public int compareTo(MethodGroup o) { return name.compareTo(o.name); } public void addMethod(MethodInfo method, int threads) { MethodInvocation mi = new MethodInvocation(method, threads); if (!methods.add(mi)) { throw new GenerationException( "Duplicate @" + Benchmark.class.getSimpleName() + " method name: " + mi.method.getQualifiedName() + ". JMH needs an uniquely named method, regardless of the arguments list. ", method); } } public Collection<MethodInfo> methods() { Collection<MethodInfo> result = new ArrayList<>(); for (MethodInvocation m : methods) { result.add(m.method); } return result; } public Optional<Integer> getTotalThreadCount() { for (Threads ann : getAll(Threads.class)) { return Optional.of(ann.value()); } return Optional.none(); } public String getName() { return name; } public void addParamValues(String name, String[] value) { if (!params.containsKey(name)) { params.put(name, value); } } public void addStrictFP(boolean sfp) { strictFP |= sfp; } public boolean isStrictFP() { return strictFP; } public void addModes(Mode eMode) { modes.add(eMode); } public void addModes(Mode[] eModes) { Collections.addAll(modes, eModes); } public Set<Mode> getModes() { return modes; } public int[] getGroupThreads() { int[] threads = new int[methods.size()]; int c = 0; for (MethodInvocation mi : methods) { threads[c++] = mi.threads; } return threads; } public Optional<Collection<String>> getGroupLabels() { if (methods.size() > 1) { Collection<String> labels = new ArrayList<>(); for (MethodInvocation mi : methods) { labels.add(mi.method.getName()); } return Optional.eitherOf(labels); } else { return Optional.none(); } } public Optional<Integer> getOperationsPerInvocation() { for (OperationsPerInvocation ann : getAll(OperationsPerInvocation.class)) { return Optional.of(ann.value()); } return Optional.none(); } public Optional<TimeUnit> getOutputTimeUnit() { for (OutputTimeUnit ann : getAll(OutputTimeUnit.class)) { return Optional.of(ann.value()); } return Optional.none(); } public Optional<Integer> getWarmupIterations() { for (Warmup ann : getAll(Warmup.class)) { if (ann.iterations() != Warmup.BLANK_ITERATIONS) { return Optional.of(ann.iterations()); } } return Optional.none(); } public Optional<TimeValue> getWarmupTime() { for (Warmup ann : getAll(Warmup.class)) { if (ann.time() != Warmup.BLANK_TIME) { return Optional.of(new TimeValue(ann.time(), ann.timeUnit())); } } return Optional.none(); } public Optional<Integer> getWarmupBatchSize() { for (Warmup ann : getAll(Warmup.class)) { if (ann.batchSize() != Warmup.BLANK_BATCHSIZE) { return Optional.of(ann.batchSize()); } } return Optional.none(); } public Optional<Integer> getMeasurementIterations() { for (Measurement ann : getAll(Measurement.class)) { if (ann.iterations() != Measurement.BLANK_ITERATIONS) { return Optional.of(ann.iterations()); } } return Optional.none(); } public Optional<TimeValue> getMeasurementTime() { for (Measurement ann : getAll(Measurement.class)) { if (ann.time() != Measurement.BLANK_TIME) { return Optional.of(new TimeValue(ann.time(), ann.timeUnit())); } } return Optional.none(); } public Optional<Integer> getMeasurementBatchSize() { for (Measurement ann : getAll(Measurement.class)) { if (ann.batchSize() != Measurement.BLANK_BATCHSIZE) { return Optional.of(ann.batchSize()); } } return Optional.none(); } public Optional<Integer> getForks() { for (Fork ann : getAll(Fork.class)) { if (ann.value() != Fork.BLANK_FORKS) { return Optional.of(ann.value()); } } return Optional.none(); } public Optional<Integer> getWarmupForks() { for (Fork ann : getAll(Fork.class)) { if (ann.warmups() != Fork.BLANK_FORKS) { return Optional.of(ann.warmups()); } } return Optional.none(); } public Optional<String> getJvm() { for (Fork ann : getAll(Fork.class)) { if (!ann.jvm().equals(Fork.BLANK_ARGS)) { return Optional.of(ann.jvm()); } } return Optional.none(); } public Optional<Collection<String>> getJvmArgs() { for (Fork ann : getAll(Fork.class)) { String[] args = ann.jvmArgs(); if (!(args.length == 1 && args[0].equals(Fork.BLANK_ARGS))) { return Optional.<Collection<String>>of(Arrays.asList(args)); } } return Optional.none(); } public Optional<Collection<String>> getJvmArgsAppend() { for (Fork ann : getAll(Fork.class)) { String[] args = ann.jvmArgsAppend(); if (!(args.length == 1 && args[0].equals(Fork.BLANK_ARGS))) { return Optional.<Collection<String>>of(Arrays.asList(args)); } } return Optional.none(); } public Optional<Collection<String>> getJvmArgsPrepend() { for (Fork ann : getAll(Fork.class)) { String[] args = ann.jvmArgsPrepend(); if (!(args.length == 1 && args[0].equals(Fork.BLANK_ARGS))) { return Optional.<Collection<String>>of(Arrays.asList(args)); } } return Optional.none(); } public Optional<TimeValue> getTimeout() { for (Timeout ann : getAll(Timeout.class)) { return Optional.of(new TimeValue(ann.time(), ann.timeUnit())); } return Optional.none(); } private <T extends Annotation> Collection<T> getAll(Class<T> annClass) { Collection<T> results = new ArrayList<>(); for (MethodInvocation mi : methods) { Collection<T> anns = BenchmarkGeneratorUtils.getAnnSuperAll(mi.method, ci, annClass); if (!(results.isEmpty() || anns.isEmpty() || results.equals(anns))) { throw new GenerationException("Colliding annotations: " + anns + " vs. " + results, mi.method); } results = anns; } return results; } public Optional<Map<String, String[]>> getParams() { Map<String, String[]> map = new TreeMap<>(); for (Map.Entry<String, String[]> e : params.entrySet()) { String key = e.getKey(); String[] values = e.getValue(); if (values.length == 1 && values[0].equalsIgnoreCase(Param.BLANK_ARGS)) { map.put(key, new String[0]); } else { map.put(key, values); } } if (params.isEmpty()) { return Optional.none(); } else { return Optional.of(map); } } }
10,034
30.958599
134
java
jmh
jmh-master/jmh-core/src/main/java/org/openjdk/jmh/generators/core/MethodInfo.java
/* * Copyright (c) 2005, 2014, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package org.openjdk.jmh.generators.core; import java.lang.annotation.Annotation; import java.util.Collection; /** * Method info. */ public interface MethodInfo extends Comparable<MethodInfo>, MetadataInfo { /** * @return short method name. */ String getName(); /** * @return fully qualified method name, includes class qualified name */ String getQualifiedName(); /** * @return fully qualified return type */ String getReturnType(); /** * @return collection of method parameters. */ Collection<ParameterInfo> getParameters(); /** * @return reference to syntactically-enclosing class */ ClassInfo getDeclaringClass(); /** * @param annClass annotation class * @param <T> annotation type * @return method-level annotation, if any; null otherwise */ <T extends Annotation> T getAnnotation(Class<T> annClass); /** * @return true, if method is public */ boolean isPublic(); /** * @return true, if method is abstract */ boolean isAbstract(); /** * @return true, if method is synchronized */ boolean isSynchronized(); /** * @return true, if method is strictfp */ boolean isStrictFP(); /** * @return true, if method is static */ boolean isStatic(); }
2,578
27.032609
79
java
jmh
jmh-master/jmh-core/src/main/java/org/openjdk/jmh/generators/core/MethodInvocation.java
/* * Copyright (c) 2005, 2014, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package org.openjdk.jmh.generators.core; class MethodInvocation implements Comparable<MethodInvocation> { public final MethodInfo method; public final int threads; public MethodInvocation(MethodInfo method, int threads) { this.method = method; this.threads = threads; } @Override public int compareTo(MethodInvocation o) { return method.getName().compareTo(o.method.getName()); } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; MethodInvocation that = (MethodInvocation) o; if (!method.getName().equals(that.method.getName())) return false; return true; } @Override public int hashCode() { return method.getName().hashCode(); } }
2,058
34.5
79
java
jmh
jmh-master/jmh-core/src/main/java/org/openjdk/jmh/generators/core/Paddings.java
/* * Copyright (c) 2014, 2014, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package org.openjdk.jmh.generators.core; import java.io.PrintWriter; import java.util.Collections; import java.util.HashMap; import java.util.Map; import java.util.StringJoiner; public class Paddings { private static final Map<String, String> PADDING_CACHE = Collections.synchronizedMap(new HashMap<>()); private static String generate(String prefix) { if (prefix.isEmpty()) { throw new IllegalArgumentException("prefix must not be empty"); } StringJoiner sj = new StringJoiner(""); for (int p = 0; p < 16; p++) { sj.add(" byte "); for (int q = 0; q < 16; q++) { if (q != 0) { sj.add(", "); } sj.add(prefix); sj.add(String.format("%03d", p * 16 + q)); } sj.add(";"); sj.add(System.lineSeparator()); } return sj.toString(); } public static void padding(PrintWriter writer, String prefix) { writer.print(PADDING_CACHE.computeIfAbsent(prefix, Paddings::generate)); } }
2,331
36.612903
80
java
jmh
jmh-master/jmh-core/src/main/java/org/openjdk/jmh/generators/core/ParameterInfo.java
/* * Copyright (c) 2005, 2014, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package org.openjdk.jmh.generators.core; /** * Method parameter metadata. */ public interface ParameterInfo extends MetadataInfo { /** * @return parameter type */ ClassInfo getType(); }
1,421
37.432432
79
java
jmh
jmh-master/jmh-core/src/main/java/org/openjdk/jmh/generators/core/SourceElementError.java
/* * Copyright (c) 2005, 2014, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package org.openjdk.jmh.generators.core; public class SourceElementError extends SourceError { private final MetadataInfo element; public SourceElementError(String message, MetadataInfo element) { super(message); this.element = element; } @Override public String toString() { return super.toString() + "\n [" + element.toString() + "]"; } }
1,608
38.243902
79
java
jmh
jmh-master/jmh-core/src/main/java/org/openjdk/jmh/generators/core/SourceElementWarning.java
/* * Copyright (c) 2005, 2014, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package org.openjdk.jmh.generators.core; public class SourceElementWarning extends SourceWarning { private final MetadataInfo element; public SourceElementWarning(String message, MetadataInfo element) { super(message); this.element = element; } @Override public String toString() { return super.toString() + "\n [" + element.toString() + "]"; } }
1,614
38.390244
79
java
jmh
jmh-master/jmh-core/src/main/java/org/openjdk/jmh/generators/core/SourceError.java
/* * Copyright (c) 2005, 2014, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package org.openjdk.jmh.generators.core; public class SourceError { private final String message; public SourceError(String message) { this.message = message; } public String getMessage() { return message; } @Override public String toString() { return message; } }
1,539
34
79
java
jmh
jmh-master/jmh-core/src/main/java/org/openjdk/jmh/generators/core/SourceThrowableError.java
/* * Copyright (c) 2005, 2014, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package org.openjdk.jmh.generators.core; import org.openjdk.jmh.util.Utils; public class SourceThrowableError extends SourceError { private final Throwable element; public SourceThrowableError(String message, Throwable element) { super(message); this.element = element; } @Override public String toString() { return super.toString() + "\n" + Utils.throwableToString(element); } }
1,646
37.302326
79
java
jmh
jmh-master/jmh-core/src/main/java/org/openjdk/jmh/generators/core/SourceThrowableWarning.java
/* * Copyright (c) 2005, 2014, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package org.openjdk.jmh.generators.core; import org.openjdk.jmh.util.Utils; public class SourceThrowableWarning extends SourceWarning { private final Throwable element; public SourceThrowableWarning(String message, Throwable element) { super(message); this.element = element; } @Override public String toString() { return super.toString() + "\n" + Utils.throwableToString(element); } }
1,652
37.44186
79
java
jmh
jmh-master/jmh-core/src/main/java/org/openjdk/jmh/generators/core/SourceWarning.java
/* * Copyright (c) 2005, 2014, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package org.openjdk.jmh.generators.core; public class SourceWarning { private final String message; public SourceWarning(String message) { this.message = message; } public String getMessage() { return message; } @Override public String toString() { return message; } }
1,543
34.090909
79
java
jmh
jmh-master/jmh-core/src/main/java/org/openjdk/jmh/generators/core/StateObject.java
/* * Copyright (c) 2005, 2014, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package org.openjdk.jmh.generators.core; import org.openjdk.jmh.annotations.Scope; import org.openjdk.jmh.util.HashMultimap; import org.openjdk.jmh.util.Multimap; import org.openjdk.jmh.util.TreeMultimap; import java.util.*; class StateObject { public static final Comparator<StateObject> ID_COMPARATOR = Comparator.comparing(o -> o.fieldIdentifier); public final String packageName; public final String userType; public final String type; public final Scope scope; public final String localIdentifier; public final String fieldIdentifier; public final Multimap<String, FieldInfo> params; public final SortedSet<HelperMethodInvocation> helpers; public final Multimap<String, String> helperArgs; public final List<StateObject> depends; public StateObject(Identifiers identifiers, ClassInfo info, Scope scope) { this.packageName = info.getPackageName() + "." + BenchmarkGenerator.JMH_GENERATED_SUBPACKAGE; this.userType = info.getQualifiedName(); this.type = identifiers.getJMHtype(info); this.scope = scope; String id = identifiers.collapseTypeName(userType) + identifiers.identifier(scope); this.localIdentifier = "l_" + id; this.fieldIdentifier = "f_" + id; this.params = new TreeMultimap<>(); this.helpers = new TreeSet<>(); this.helperArgs = new HashMultimap<>(); this.depends = new ArrayList<>(); } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; StateObject that = (StateObject) o; if (!fieldIdentifier.equals(that.fieldIdentifier)) return false; if (scope != that.scope) return false; if (!Objects.equals(type, that.type)) return false; return true; } @Override public int hashCode() { int result = type != null ? type.hashCode() : 0; result = 31 * result + (scope != null ? scope.hashCode() : 0); result = 31 * result + (fieldIdentifier.hashCode()); return result; } public String toTypeDef() { return type + " " + localIdentifier; } public String toLocal() { return localIdentifier; } public Collection<String> getParamsLabels() { return params.keys(); } public void addParam(FieldInfo fieldInfo) { params.put(fieldInfo.getName(), fieldInfo); } public Collection<FieldInfo> getParam(String name) { return params.get(name); } public String getParamAccessor(FieldInfo paramField) { String name = paramField.getName(); String type = paramField.getType().getQualifiedName(); if (type.equalsIgnoreCase("java.lang.String")) { return "control.getParam(\"" + name + "\")"; } if (type.equalsIgnoreCase("boolean") || type.equalsIgnoreCase("java.lang.Boolean")) { return "Boolean.valueOf(control.getParam(\"" + name + "\"))"; } if (type.equalsIgnoreCase("byte") || type.equalsIgnoreCase("java.lang.Byte")) { return "Byte.valueOf(control.getParam(\"" + name + "\"))"; } if (type.equalsIgnoreCase("char") || type.equalsIgnoreCase("java.lang.Character")) { return "(control.getParam(\"" + name + "\")).charAt(0)"; } if (type.equalsIgnoreCase("short") || type.equalsIgnoreCase("java.lang.Short")) { return "Short.valueOf(control.getParam(\"" + name + "\"))"; } if (type.equalsIgnoreCase("int") || type.equalsIgnoreCase("java.lang.Integer")) { return "Integer.valueOf(control.getParam(\"" + name + "\"))"; } if (type.equalsIgnoreCase("float") || type.equalsIgnoreCase("java.lang.Float")) { return "Float.valueOf(control.getParam(\"" + name + "\"))"; } if (type.equalsIgnoreCase("long") || type.equalsIgnoreCase("java.lang.Long")) { return "Long.valueOf(control.getParam(\"" + name + "\"))"; } if (type.equalsIgnoreCase("double") || type.equalsIgnoreCase("java.lang.Double")) { return "Double.valueOf(control.getParam(\"" + name + "\"))"; } // assume enum return type + ".valueOf(control.getParam(\"" + name + "\"))"; } public void addHelper(HelperMethodInvocation hmi) { helpers.add(hmi); } public Collection<HelperMethodInvocation> getHelpers() { return helpers; } }
5,747
36.815789
109
java
jmh
jmh-master/jmh-core/src/main/java/org/openjdk/jmh/generators/core/StateObjectHandler.java
/* * Copyright (c) 2005, 2022, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package org.openjdk.jmh.generators.core; import org.openjdk.jmh.annotations.*; import org.openjdk.jmh.infra.*; import org.openjdk.jmh.util.HashMultimap; import org.openjdk.jmh.util.Multimap; import org.openjdk.jmh.util.Utils; import java.io.IOException; import java.io.PrintWriter; import java.lang.annotation.Annotation; import java.lang.annotation.IncompleteAnnotationException; import java.util.*; import java.util.concurrent.atomic.AtomicIntegerFieldUpdater; class StateObjectHandler { private final CompilerControlPlugin compileControl; private final Identifiers identifiers; private final Multimap<String, StateObject> roots; private final Multimap<String, ClassInfo> specials; private final Set<StateObject> stateObjects; private final Map<String, StateObject> implicits; private final Multimap<String, String> benchmarkArgs; private final Multimap<String, String> auxNames = new HashMultimap<>(); private final Map<String, AuxCounters.Type> auxType = new HashMap<>(); private final Map<String, String> auxAccessors = new HashMap<>(); private final Map<String, Boolean> auxResettable = new HashMap<>(); public StateObjectHandler(CompilerControlPlugin compileControl) { this.compileControl = compileControl; this.roots = new HashMultimap<>(); this.benchmarkArgs = new HashMultimap<>(); this.implicits = new HashMap<>(); this.specials = new HashMultimap<>(); this.stateObjects = new HashSet<>(); this.identifiers = new Identifiers(); } public static void validateState(ClassInfo state) { // Because of https://bugs.openjdk.java.net/browse/JDK-8031122, // we need to preemptively check the annotation value, and // the API can only allow that by catching the exception, argh. try { State ann = BenchmarkGeneratorUtils.getAnnSuper(state, State.class); if (ann != null) { ann.value(); } } catch (IncompleteAnnotationException iae) { throw new GenerationException("The @" + State.class.getSimpleName() + " annotation should have the explicit " + Scope.class.getSimpleName() + " argument", state); } if (!state.isPublic()) { throw new GenerationException("The instantiated @" + State.class.getSimpleName() + " annotation only supports public classes.", state); } if (state.isFinal()) { throw new GenerationException("The instantiated @" + State.class.getSimpleName() + " annotation does not support final classes." , state); } if (state.isInner()) { throw new GenerationException("The instantiated @" + State.class.getSimpleName() + " annotation does not support inner classes, make sure your class is static.", state); } if (state.isAbstract()) { throw new GenerationException("The instantiated @" + State.class.getSimpleName() + " class cannot be abstract.", state); } boolean hasDefaultConstructor = false; for (MethodInfo constructor : state.getConstructors()) { if (constructor.getParameters().isEmpty()) { hasDefaultConstructor = constructor.isPublic(); break; } } // These classes use the special init sequence: hasDefaultConstructor |= state.getQualifiedName().equals(BenchmarkParams.class.getCanonicalName()); hasDefaultConstructor |= state.getQualifiedName().equals(IterationParams.class.getCanonicalName()); hasDefaultConstructor |= state.getQualifiedName().equals(ThreadParams.class.getCanonicalName()); if (!hasDefaultConstructor) { throw new GenerationException("The @" + State.class.getSimpleName() + " annotation can only be applied to the classes having the default public constructor.", state); } // validate rogue annotations on classes BenchmarkGeneratorUtils.checkAnnotations(state); for (FieldInfo fi : BenchmarkGeneratorUtils.getAllFields(state)) { BenchmarkGeneratorUtils.checkAnnotations(fi); } // validate rogue annotations on methods for (MethodInfo mi : BenchmarkGeneratorUtils.getAllMethods(state)) { BenchmarkGeneratorUtils.checkAnnotations(mi); } // check @Setup/@TearDown have only @State arguments for (MethodInfo mi : BenchmarkGeneratorUtils.getAllMethods(state)) { if (mi.getAnnotation(Setup.class) != null || mi.getAnnotation(TearDown.class) != null) { validateStateArgs(mi); } } } public static void validateStateArgs(MethodInfo e) { for (ParameterInfo var : e.getParameters()) { if (BenchmarkGeneratorUtils.getAnnSuper(var.getType(), State.class) != null) continue; if (isSpecialClass(var.getType())) continue; throw new GenerationException( "Method parameters should be either @" + State.class.getSimpleName() + " classes or one of special JMH classes (*Params, Blackhole, Control)", e); } } private static boolean isSpecialClass(ClassInfo ci) { String name = ci.getQualifiedName(); return name.equals(BenchmarkParams.class.getCanonicalName()) || name.equals(IterationParams.class.getCanonicalName()) || name.equals(ThreadParams.class.getCanonicalName()) || name.equals(Blackhole.class.getCanonicalName()) || name.equals(Control.class.getCanonicalName()) ; } private String getSpecialClassAccessor(ClassInfo pci) { String name = pci.getQualifiedName(); if (name.equals(BenchmarkParams.class.getCanonicalName())) return "benchmarkParams"; if (name.equals(IterationParams.class.getCanonicalName())) return "iterationParams"; if (name.equals(ThreadParams.class.getCanonicalName())) return "threadParams"; if (name.equals(Blackhole.class.getCanonicalName())) return "blackhole"; if (name.equals(Control.class.getCanonicalName())) return "notifyControl"; throw new GenerationException("Internal error, unhandled special class: " + pci, pci); } public State getState(ClassInfo ci, ParameterInfo pi) { State ann = BenchmarkGeneratorUtils.getAnnSuper(ci, State.class); if (ann == null) { throw new GenerationException("The method parameter is not a @" + State.class.getSimpleName() + ": ", pi); } return ann; } public void bindMethods(ClassInfo holder, MethodGroup mg) { for (MethodInfo method : mg.methods()) { // Bind the holder implicitly: { State ann = BenchmarkGeneratorUtils.getAnnSuper(holder, State.class); Scope scope = (ann != null) ? ann.value() : Scope.Thread; StateObject holderSo = new StateObject(identifiers, holder, scope); stateObjects.add(holderSo); implicits.put("bench", holderSo); bindState(method, holderSo, holder); resolveDependencies(method, holder, holderSo); } // Check that all arguments are states. validateStateArgs(method); // Bind all @Benchmark parameters for (ParameterInfo ppi : method.getParameters()) { ClassInfo pci = ppi.getType(); if (isSpecialClass(pci)) { benchmarkArgs.put(method.getName(), getSpecialClassAccessor(pci)); specials.put(method.getName(), pci); } else { StateObject pso = new StateObject(identifiers, pci, getState(pci, ppi).value()); stateObjects.add(pso); roots.put(method.getName(), pso); benchmarkArgs.put(method.getName(), pso.toLocal()); bindState(method, pso, pci); resolveDependencies(method, pci, pso); } } } } public static void validateNoCycles(MethodInfo method) { validateNoCyclesStep(Collections.<ClassQName>emptySet(), method, true); } private static void validateNoCyclesStep(Set<ClassQName> alreadySeen, MethodInfo method, boolean includeHolder) { // Collect and check outgoing edges Set<ClassQName> outgoing = new HashSet<>(); if (includeHolder) { outgoing.add(new ClassQName(method.getDeclaringClass())); } for (ParameterInfo ppi : method.getParameters()) { outgoing.add(new ClassQName(ppi.getType())); } if (outgoing.isEmpty()) { // No outgoing edges, checks complete. return; } Set<ClassQName> currentSeen = new HashSet<>(); currentSeen.addAll(alreadySeen); for (ClassQName ci : outgoing) { // Try see if we have already seen these edges for current method. // If so, this is a dependency cycle. if (!currentSeen.add(ci)) { throw new GenerationException("@" + State.class.getSimpleName() + " dependency cycle is detected: " + ci.ci.getQualifiedName() + " " + currentSeen, method); } // For each fixture method that needs the state, see if we need to initialize those as well. // Restart the search from already seen + the outgoing edge. Set<ClassQName> nextSeen = new HashSet<>(); nextSeen.addAll(alreadySeen); nextSeen.add(ci); for (MethodInfo mi : BenchmarkGeneratorUtils.getAllMethods(ci.ci)) { if (mi.getAnnotation(Setup.class) != null || mi.getAnnotation(TearDown.class) != null) { validateNoCyclesStep(nextSeen, mi, false); } } } } private static class ClassQName { private final ClassInfo ci; private ClassQName(ClassInfo ci) { this.ci = ci; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; ClassQName cycleInfo = (ClassQName) o; return Objects.equals(ci.getQualifiedName(), cycleInfo.ci.getQualifiedName()); } @Override public int hashCode() { return Objects.hash(ci.getQualifiedName()); } } /** * Recursively resolve if there are any other states referenced through helper methods. */ private void resolveDependencies(MethodInfo method, ClassInfo pci, StateObject pso) { for (MethodInfo mi : BenchmarkGeneratorUtils.getAllMethods(pci)) { if (mi.getAnnotation(Setup.class) != null || mi.getAnnotation(TearDown.class) != null) { for (ParameterInfo pi : mi.getParameters()) { ClassInfo ci = pi.getType(); if (isSpecialClass(ci)) { pso.helperArgs.put(mi.getQualifiedName(), getSpecialClassAccessor(ci)); specials.put(mi.getQualifiedName(), ci); } else { StateObject so = new StateObject(identifiers, ci, getState(ci, pi).value()); stateObjects.add(so); pso.helperArgs.put(mi.getQualifiedName(), so.toLocal()); if (!pso.depends.contains(so)) { pso.depends.add(so); bindState(method, so, ci); resolveDependencies(method, ci, so); } } } } } } private void bindState(MethodInfo execMethod, StateObject so, ClassInfo ci) { // Check it is a valid state validateState(ci); // auxiliary result, produce the accessors AuxCounters auxCountAnn = ci.getAnnotation(AuxCounters.class); if (auxCountAnn != null) { if (so.scope != Scope.Thread) { throw new GenerationException("@" + AuxCounters.class.getSimpleName() + " can only be used with " + Scope.class.getSimpleName() + "." + Scope.Thread + " states.", ci); } for (FieldInfo sub : ci.getFields()) { if (sub.isPublic()) { if (!isAuxCompatible(sub.getType().getQualifiedName())) { throw new GenerationException("Illegal type for the public field in @" + AuxCounters.class.getSimpleName() + ".", sub); } String name = sub.getName(); String meth = execMethod.getName(); auxNames.put(meth, name); auxType.put(name, auxCountAnn.value()); auxResettable.put(name, true); String prev = auxAccessors.put(meth + name, so.localIdentifier + "." + name); if (prev != null) { throw new GenerationException("Conflicting @" + AuxCounters.class.getSimpleName() + " counters. Make sure there are no @" + State.class.getSimpleName() + "-s with the same counter " + " injected into this method.", sub); } } } for (MethodInfo sub : ci.getMethods()) { if (sub.isPublic() && !sub.getReturnType().equals("void")) { if (!isAuxCompatible(sub.getReturnType())) { throw new GenerationException("Illegal type for the return type of public method in @" + AuxCounters.class.getSimpleName() + ".", sub); } String name = sub.getName(); String meth = execMethod.getName(); auxNames.put(meth, name); auxType.put(name, auxCountAnn.value()); auxResettable.put(name, false); String prev = auxAccessors.put(meth + name, so.localIdentifier + "." + name + "()"); if (prev != null) { throw new GenerationException("Conflicting @" + AuxCounters.class.getSimpleName() + " counters. Make sure there are no @" + State.class.getSimpleName() + "-s with the same counter " + " injected into this method.", sub); } } } } // walk the type hierarchy up to discover inherited @Params for (FieldInfo fi : BenchmarkGeneratorUtils.getAllFields(ci)) { if (fi.getAnnotation(Param.class) != null) { checkParam(fi); so.addParam(fi); } } // put the @State objects helper methods for (MethodInfo mi : BenchmarkGeneratorUtils.getAllMethods(ci)) { Setup setupAnn = mi.getAnnotation(Setup.class); if (setupAnn != null) { checkHelpers(mi, Setup.class); so.addHelper(new HelperMethodInvocation(mi, so, setupAnn.value(), HelperType.SETUP)); compileControl.defaultForceInline(mi); } TearDown tearDownAnn = mi.getAnnotation(TearDown.class); if (tearDownAnn != null) { checkHelpers(mi, TearDown.class); so.addHelper(new HelperMethodInvocation(mi, so, tearDownAnn.value(), HelperType.TEARDOWN)); compileControl.defaultForceInline(mi); } } } private boolean isAuxCompatible(String typeName) { if (typeName.equals("byte") || typeName.equals("java.lang.Byte")) return true; if (typeName.equals("short") || typeName.equals("java.lang.Short")) return true; if (typeName.equals("int") || typeName.equals("java.lang.Integer")) return true; if (typeName.equals("float") || typeName.equals("java.lang.Float")) return true; if (typeName.equals("long") || typeName.equals("java.lang.Long")) return true; if (typeName.equals("double") || typeName.equals("java.lang.Double")) return true; return false; } private void checkParam(FieldInfo fi) { if (fi.isFinal()) { throw new GenerationException( "@" + Param.class.getSimpleName() + " annotation is not acceptable on final fields.", fi); } if (BenchmarkGeneratorUtils.getAnnSyntax(fi.getDeclaringClass(), State.class) == null) { throw new GenerationException( "@" + Param.class.getSimpleName() + " annotation should be placed in @" + State.class.getSimpleName() + "-annotated class.", fi); } ClassInfo type = fi.getType(); if (!isParamTypeAcceptable(type)) { throw new GenerationException( "@" + Param.class.getSimpleName() + " can only be placed over the annotation-compatible types:" + " primitives, primitive wrappers, Strings, or enums.", fi); } String[] values = fi.getAnnotation(Param.class).value(); if (values.length == 1 && values[0].equalsIgnoreCase(Param.BLANK_ARGS)) { if (!fi.getType().isEnum()) { throw new GenerationException( "@" + Param.class.getSimpleName() + " should provide the default parameters.", fi); } else { // if type is enum then don't need to check conformity } } else { for (String val : values) { if (!isParamValueConforming(fi, val, type)) { throw new GenerationException( "Some @" + Param.class.getSimpleName() + " values can not be converted to target type: " + "\"" + val + "\" can not be converted to " + type, fi ); } } } } private boolean isParamTypeAcceptable(ClassInfo type) { String typeName = type.getQualifiedName(); if (type.isEnum()) return true; if (typeName.equals("java.lang.String")) return true; if (typeName.equals("boolean") || typeName.equals("java.lang.Boolean")) return true; if (typeName.equals("byte") || typeName.equals("java.lang.Byte")) return true; if (typeName.equals("char") || typeName.equals("java.lang.Character")) return true; if (typeName.equals("short") || typeName.equals("java.lang.Short")) return true; if (typeName.equals("int") || typeName.equals("java.lang.Integer")) return true; if (typeName.equals("float") || typeName.equals("java.lang.Float")) return true; if (typeName.equals("long") || typeName.equals("java.lang.Long")) return true; if (typeName.equals("double") || typeName.equals("java.lang.Double")) return true; return false; } private boolean isParamValueConforming(FieldInfo fi, String val, ClassInfo type) { String typeName = type.getQualifiedName(); if (type.isEnum()) { if (type.getEnumConstants().contains(val)) { return true; } } if (typeName.equals("java.lang.String")) { return true; } if (typeName.equals("boolean") || typeName.equals("java.lang.Boolean")) { return (val.equals("true") || val.equals("false")); } if (typeName.equals("byte") || typeName.equals("java.lang.Byte")) { try { Byte.parseByte(val); return true; } catch (NumberFormatException nfe) { return false; } } if (typeName.equals("char") || typeName.equals("java.lang.Character")) { return (val.length() == 1); } if (typeName.equals("short") || typeName.equals("java.lang.Short")) { try { Short.parseShort(val); return true; } catch (NumberFormatException nfe) { return false; } } if (typeName.equals("int") || typeName.equals("java.lang.Integer")) { try { Integer.parseInt(val); return true; } catch (NumberFormatException nfe) { return false; } } if (typeName.equals("float") || typeName.equals("java.lang.Float")) { try { Float.parseFloat(val); return true; } catch (NumberFormatException nfe) { return false; } } if (typeName.equals("long") || typeName.equals("java.lang.Long")) { try { Long.parseLong(val); return true; } catch (NumberFormatException nfe) { return false; } } if (typeName.equals("double") || typeName.equals("java.lang.Double")) { try { Double.parseDouble(val); return true; } catch (NumberFormatException nfe) { return false; } } return false; } private void checkHelpers(MethodInfo mi, Class<? extends Annotation> annClass) { // OK to have these annotation for @State objects if (BenchmarkGeneratorUtils.getAnnSuper(mi.getDeclaringClass(), State.class) == null) { if (!mi.getDeclaringClass().isAbstract()) { throw new GenerationException( "@" + annClass.getSimpleName() + " annotation is placed within " + "a class not having @" + State.class.getSimpleName() + " annotation. " + "This is prohibited because it would have no effect.", mi); } } if (!mi.isPublic()) { throw new GenerationException( "@" + annClass.getSimpleName() + " method should be public.", mi); } if (!mi.getReturnType().equalsIgnoreCase("void")) { throw new GenerationException( "@" + annClass.getSimpleName() + " method should not return anything.", mi); } } public String getBenchmarkArgList(MethodInfo methodInfo) { return Utils.join(benchmarkArgs.get(methodInfo.getName()), ", "); } public String getArgList(MethodInfo methodInfo) { return getArgList(stateOrder(methodInfo, false)); } public String getArgList(Collection<StateObject> sos) { StringBuilder sb = new StringBuilder(); int i = 0; for (StateObject so : sos) { if (i != 0) { sb.append(", "); } sb.append(so.toLocal()); i++; } return sb.toString(); } public String getTypeArgList(MethodInfo methodInfo) { return getTypeArgList(stateOrder(methodInfo, false)); } public String getTypeArgList(Collection<StateObject> sos) { StringBuilder sb = new StringBuilder(); int i = 0; for (StateObject so : sos) { if (i != 0) { sb.append(", "); } sb.append(so.toTypeDef()); i++; } return sb.toString(); } @SafeVarargs public static Collection<StateObject> cons(Collection<StateObject>... colls) { SortedSet<StateObject> r = new TreeSet<>(StateObject.ID_COMPARATOR); for (Collection<StateObject> coll : colls) { r.addAll(coll); } return r; } public Collection<String> getHelperBlock(MethodInfo method, Level helperLevel, HelperType type) { // Look for the offending methods. // This will be used to skip the irrelevant blocks for state objects down the stream. List<StateObject> statesForward = new ArrayList<>(); for (StateObject so : stateOrder(method, true)) { for (HelperMethodInvocation hmi : so.getHelpers()) { if (hmi.helperLevel == helperLevel) { statesForward.add(so); break; } } } List<StateObject> statesReverse = new ArrayList<>(); for (StateObject so : stateOrder(method, false)) { for (HelperMethodInvocation hmi : so.getHelpers()) { if (hmi.helperLevel == helperLevel) { statesReverse.add(so); break; } } } List<String> result = new ArrayList<>(); // Handle Thread object helpers for (StateObject so : statesForward) { if (type != HelperType.SETUP) continue; if (so.scope == Scope.Thread) { for (HelperMethodInvocation mi : so.getHelpers()) { if (mi.helperLevel == helperLevel && mi.type == HelperType.SETUP) { Collection<String> args = so.helperArgs.get(mi.method.getQualifiedName()); result.add(so.localIdentifier + "." + mi.method.getName() + "(" + Utils.join(args, ",") + ");"); } } } if (so.scope == Scope.Benchmark || so.scope == Scope.Group) { result.add("if (" + so.type + ".setup" + helperLevel + "MutexUpdater.compareAndSet(" + so.localIdentifier + ", 0, 1)) {"); result.add(" try {"); result.add(" if (control.isFailing) throw new FailureAssistException();"); result.add(" if (!" + so.localIdentifier + ".ready" + helperLevel + ") {"); for (HelperMethodInvocation mi : so.getHelpers()) { if (mi.helperLevel == helperLevel && mi.type == HelperType.SETUP) { Collection<String> args = so.helperArgs.get(mi.method.getQualifiedName()); result.add(" " + so.localIdentifier + "." + mi.method.getName() + "(" + Utils.join(args, ",") + ");"); } } result.add(" " + so.localIdentifier + ".ready" + helperLevel + " = true;"); result.add(" }"); result.add(" } catch (Throwable t) {"); result.add(" control.isFailing = true;"); result.add(" throw t;"); result.add(" } finally {"); result.add(" " + so.type + ".setup" + helperLevel + "MutexUpdater.set(" + so.localIdentifier + ", 0);"); result.add(" }"); result.add("} else {"); result.add(" while (" + so.type + ".setup" + helperLevel + "MutexUpdater.get(" + so.localIdentifier + ") == 1) {"); result.add(" if (control.isFailing) throw new FailureAssistException();"); result.add(" if (Thread.interrupted()) throw new InterruptedException();"); result.add(" }"); result.add("}"); } } for (StateObject so : statesReverse) { if (type != HelperType.TEARDOWN) continue; if (so.scope == Scope.Thread) { for (HelperMethodInvocation mi : so.getHelpers()) { if (mi.helperLevel == helperLevel && mi.type == HelperType.TEARDOWN) { Collection<String> args = so.helperArgs.get(mi.method.getQualifiedName()); result.add(so.localIdentifier + "." + mi.method.getName() + "(" + Utils.join(args, ",") + ");"); } } } if (so.scope == Scope.Benchmark || so.scope == Scope.Group) { result.add("if (" + so.type + ".tear" + helperLevel + "MutexUpdater.compareAndSet(" + so.localIdentifier + ", 0, 1)) {"); result.add(" try {"); result.add(" if (control.isFailing) throw new FailureAssistException();"); result.add(" if (" + so.localIdentifier + ".ready" + helperLevel + ") {"); for (HelperMethodInvocation mi : so.getHelpers()) { if (mi.helperLevel == helperLevel && mi.type == HelperType.TEARDOWN) { Collection<String> args = so.helperArgs.get(mi.method.getQualifiedName()); result.add(" " + so.localIdentifier + "." + mi.method.getName() + "(" + Utils.join(args, ",") + ");"); } } result.add(" " + so.localIdentifier + ".ready" + helperLevel + " = false;"); result.add(" }"); result.add(" } catch (Throwable t) {"); result.add(" control.isFailing = true;"); result.add(" throw t;"); result.add(" } finally {"); result.add(" " + so.type + ".tear" + helperLevel + "MutexUpdater.set(" + so.localIdentifier + ", 0);"); result.add(" }"); result.add("} else {"); // We don't need to actively busy-wait for Trial, it is way past the measurement window, // and we would not need measurement threads anymore after this is over. Therefore, it // is OK to exponentially back off. if (helperLevel == Level.Trial) { result.add(" long " + so.localIdentifier + "_backoff = 1;"); } result.add(" while (" + so.type + ".tear" + helperLevel + "MutexUpdater.get(" + so.localIdentifier + ") == 1) {"); if (helperLevel == Level.Trial) { result.add(" TimeUnit.MILLISECONDS.sleep(" + so.localIdentifier + "_backoff);"); result.add(" " + so.localIdentifier + "_backoff = Math.max(1024, " + so.localIdentifier + "_backoff * 2);"); } result.add(" if (control.isFailing) throw new FailureAssistException();"); result.add(" if (Thread.interrupted()) throw new InterruptedException();"); result.add(" }"); result.add("}"); } } return result; } public boolean hasInvocationStubs(MethodInfo method) { return !getInvocationSetups(method).isEmpty() || !getInvocationTearDowns(method).isEmpty(); } public Collection<String> getInvocationSetups(MethodInfo method) { return getHelperBlock(method, Level.Invocation, HelperType.SETUP); } public Collection<String> getInvocationTearDowns(MethodInfo method) { return getHelperBlock(method, Level.Invocation, HelperType.TEARDOWN); } public Collection<String> getIterationSetups(MethodInfo method) { return getHelperBlock(method, Level.Iteration, HelperType.SETUP); } public Collection<String> getIterationTearDowns(MethodInfo method) { return getHelperBlock(method, Level.Iteration, HelperType.TEARDOWN); } public Collection<String> getRunSetups(MethodInfo method) { return getHelperBlock(method, Level.Trial, HelperType.SETUP); } public Collection<String> getRunTearDowns(MethodInfo method) { return getHelperBlock(method, Level.Trial, HelperType.TEARDOWN); } public List<String> getStateInitializers() { Collection<StateObject> sos = cons(stateObjects); List<String> result = new ArrayList<>(); for (StateObject so : sos) { if (so.scope != Scope.Benchmark) continue; result.add(""); result.add("static volatile " + so.type + " " + so.fieldIdentifier + ";"); result.add(""); result.add(so.type + " _jmh_tryInit_" + so.fieldIdentifier + "(InfraControl control" + soDependency_TypeArgs(so) + ") throws Throwable {"); result.add(" " + so.type + " val = " + so.fieldIdentifier + ";"); result.add(" if (val != null) {"); result.add(" return val;"); result.add(" }"); result.add(" synchronized(this.getClass()) {"); result.add(" try {"); result.add(" if (control.isFailing) throw new FailureAssistException();"); result.add(" val = " + so.fieldIdentifier + ";"); result.add(" if (val != null) {"); result.add(" return val;"); result.add(" }"); result.add(" val = new " + so.type + "();"); if (!so.getParamsLabels().isEmpty()) { result.add(" Field f;"); } for (String paramName : so.getParamsLabels()) { for (FieldInfo paramField : so.getParam(paramName)) { result.add(" f = " + paramField.getDeclaringClass().getQualifiedName() + ".class.getDeclaredField(\"" + paramName + "\");"); result.add(" f.setAccessible(true);"); result.add(" f.set(val, " + so.getParamAccessor(paramField) + ");"); } } for (HelperMethodInvocation hmi : so.getHelpers()) { if (hmi.helperLevel != Level.Trial) continue; if (hmi.type != HelperType.SETUP) continue; Collection<String> args = so.helperArgs.get(hmi.method.getQualifiedName()); result.add(" val." + hmi.method.getName() + "(" + Utils.join(args, ",") + ");"); } result.add(" val.ready" + Level.Trial + " = true;"); result.add(" " + so.fieldIdentifier + " = val;"); result.add(" } catch (Throwable t) {"); result.add(" control.isFailing = true;"); result.add(" throw t;"); result.add(" }"); result.add(" }"); result.add(" return val;"); result.add("}"); } for (StateObject so : sos) { if (so.scope != Scope.Thread) continue; result.add(""); result.add(so.type + " " + so.fieldIdentifier + ";"); result.add(""); result.add(so.type + " _jmh_tryInit_" + so.fieldIdentifier + "(InfraControl control" + soDependency_TypeArgs(so) + ") throws Throwable {"); result.add(" if (control.isFailing) throw new FailureAssistException();"); result.add(" " + so.type + " val = " + so.fieldIdentifier + ";"); result.add(" if (val == null) {"); result.add(" val = new " + so.type + "();"); if (!so.getParamsLabels().isEmpty()) { result.add(" Field f;"); } for (String paramName : so.getParamsLabels()) { for (FieldInfo paramField : so.getParam(paramName)) { result.add(" f = " + paramField.getDeclaringClass().getQualifiedName() + ".class.getDeclaredField(\"" + paramName + "\");"); result.add(" f.setAccessible(true);"); result.add(" f.set(val, " + so.getParamAccessor(paramField) + ");"); } } for (HelperMethodInvocation hmi : so.getHelpers()) { if (hmi.helperLevel != Level.Trial) continue; if (hmi.type != HelperType.SETUP) continue; Collection<String> args = so.helperArgs.get(hmi.method.getQualifiedName()); result.add(" val." + hmi.method.getName() + "(" + Utils.join(args, ",") + ");"); } result.add(" " + so.fieldIdentifier + " = val;"); result.add(" }"); result.add(" return val;"); result.add("}"); } for (StateObject so : sos) { if (so.scope != Scope.Group) continue; result.add(""); result.add("static java.util.Map<Integer, " + so.type + "> " + so.fieldIdentifier + "_map = java.util.Collections.synchronizedMap(new java.util.HashMap<Integer, " + so.type + ">());"); result.add(""); result.add(so.type + " _jmh_tryInit_" + so.fieldIdentifier + "(InfraControl control" + soDependency_TypeArgs(so) + ") throws Throwable {"); result.add(" int groupIdx = threadParams.getGroupIndex();"); result.add(" " + so.type + " val = " + so.fieldIdentifier + "_map.get(groupIdx);"); result.add(" if (val != null) {"); result.add(" return val;"); result.add(" }"); result.add(" synchronized(this.getClass()) {"); result.add(" try {"); result.add(" if (control.isFailing) throw new FailureAssistException();"); result.add(" val = " + so.fieldIdentifier + "_map.get(groupIdx);"); result.add(" if (val != null) {"); result.add(" return val;"); result.add(" }"); result.add(" val = new " + so.type + "();"); if (!so.getParamsLabels().isEmpty()) { result.add(" Field f;"); } for (String paramName : so.getParamsLabels()) { for(FieldInfo paramField : so.getParam(paramName)) { result.add(" f = " + paramField.getDeclaringClass().getQualifiedName() + ".class.getDeclaredField(\"" + paramName + "\");"); result.add(" f.setAccessible(true);"); result.add(" f.set(val, " + so.getParamAccessor(paramField) + ");"); } } for (HelperMethodInvocation hmi : so.getHelpers()) { if (hmi.helperLevel != Level.Trial) continue; if (hmi.type != HelperType.SETUP) continue; Collection<String> args = so.helperArgs.get(hmi.method.getQualifiedName()); result.add(" val." + hmi.method.getName() + "(" + Utils.join(args, ",") + ");"); } result.add(" " + "val.ready" + Level.Trial + " = true;"); result.add(" " + so.fieldIdentifier + "_map.put(groupIdx, val);"); result.add(" } catch (Throwable t) {"); result.add(" control.isFailing = true;"); result.add(" throw t;"); result.add(" }"); result.add(" }"); result.add(" return val;"); result.add("}"); } return result; } private String soDependency_TypeArgs(StateObject so) { return (so.depends.isEmpty() ? "" : ", " + getTypeArgList(so.depends)); } private String soDependency_Args(StateObject so) { return (so.depends.isEmpty() ? "" : ", " + getArgList(so.depends)); } public Collection<String> getStateDestructors(MethodInfo method) { Collection<StateObject> sos = stateOrder(method, false); List<String> result = new ArrayList<>(); for (StateObject so : sos) { if (so.scope != Scope.Benchmark) continue; result.add("synchronized(this.getClass()) {"); result.add(" " + so.fieldIdentifier + " = null;"); result.add("}"); } for (StateObject so : sos) { if (so.scope != Scope.Thread) continue; result.add("" + so.fieldIdentifier + " = null;"); } for (StateObject so : sos) { if (so.scope != Scope.Group) continue; result.add("synchronized(this.getClass()) {"); result.add(" " + so.fieldIdentifier + "_map.remove(threadParams.getGroupIndex());"); result.add("}"); } return result; } public List<String> getStateGetters(MethodInfo method) { List<String> result = new ArrayList<>(); for (StateObject so : stateOrder(method, true)) { result.add(so.type + " " + so.localIdentifier + " = _jmh_tryInit_" + so.fieldIdentifier + "(control" + soDependency_Args(so) + ");"); } return result; } private LinkedHashSet<StateObject> stateOrder(MethodInfo method, boolean reverse) { // Linearize @State dependency DAG List<StateObject> linearOrder = new ArrayList<>(); List<StateObject> stratum = new ArrayList<>(); // These are roots stratum.addAll(roots.get(method.getName())); stratum.addAll(implicits.values()); // Recursively walk the DAG while (!stratum.isEmpty()) { linearOrder.addAll(stratum); List<StateObject> newStratum = new ArrayList<>(); for (StateObject so : stratum) { newStratum.addAll(so.depends); } stratum = newStratum; } if (reverse) { Collections.reverse(linearOrder); } return new LinkedHashSet<>(linearOrder); } public void writeStateOverrides(BenchmarkGeneratorSession sess, GeneratorDestination dst) throws IOException { for (StateObject so : cons(stateObjects)) { if (!sess.generatedStateOverrides.add(so.userType)) continue; { PrintWriter pw = new PrintWriter(dst.newClass(so.packageName + "." + so.type + "_B1", so.userType)); pw.println("package " + so.packageName + ";"); pw.println("import " + so.userType + ";"); pw.println("public class " + so.type + "_B1 extends " + so.userType + " {"); Paddings.padding(pw, "b1_"); pw.println("}"); pw.close(); } { PrintWriter pw = new PrintWriter(dst.newClass(so.packageName + "." + so.type + "_B2", so.userType)); pw.println("package " + so.packageName + ";"); pw.println("import " + AtomicIntegerFieldUpdater.class.getCanonicalName() + ";"); pw.println("public class " + so.type + "_B2 extends " + so.type + "_B1 {"); for (Level level : Level.values()) { pw.println(" public volatile int setup" + level + "Mutex;"); pw.println(" public volatile int tear" + level + "Mutex;"); pw.println(" public final static AtomicIntegerFieldUpdater<" + so.type + "_B2> setup" + level + "MutexUpdater = " + "AtomicIntegerFieldUpdater.newUpdater(" + so.type + "_B2.class, \"setup" + level + "Mutex\");"); pw.println(" public final static AtomicIntegerFieldUpdater<" + so.type + "_B2> tear" + level + "MutexUpdater = " + "AtomicIntegerFieldUpdater.newUpdater(" + so.type + "_B2.class, \"tear" + level + "Mutex\");"); pw.println(""); } switch (so.scope) { case Benchmark: case Group: for (Level level : Level.values()) { pw.println(" public volatile boolean ready" + level + ";"); } break; case Thread: // these flags are redundant for single thread break; default: throw new IllegalStateException("Unknown state scope: " + so.scope); } pw.println("}"); pw.close(); } { PrintWriter pw = new PrintWriter(dst.newClass(so.packageName + "." + so.type + "_B3", so.userType)); pw.println("package " + so.packageName + ";"); pw.println("public class " + so.type + "_B3 extends " + so.type + "_B2 {"); Paddings.padding(pw, "b3_"); pw.println("}"); pw.println(""); pw.close(); } { PrintWriter pw = new PrintWriter(dst.newClass(so.packageName + "." + so.type, so.userType)); pw.println("package " + so.packageName + ";"); pw.println("public class " + so.type + " extends " + so.type + "_B3 {"); pw.println("}"); pw.println(""); pw.close(); } } } public Collection<String> getFields() { return Collections.emptyList(); } public StateObject getImplicit(String label) { return implicits.get(label); } public void addImports(PrintWriter writer) { for (StateObject so : cons(stateObjects)) { writer.println("import " + so.packageName + "." + so.type + ";"); } } public Collection<String> getAuxResets(MethodInfo method) { Collection<String> result = new ArrayList<>(); for (String name : auxNames.get(method.getName())) { if (auxResettable.get(name)) { result.add(auxAccessors.get(method.getName() + name) + " = 0;"); } } return result; } public Collection<String> getAuxResults(MethodInfo method, String opResName) { Collection<String> result = new ArrayList<>(); for (String ops : auxNames.get(method.getName())) { AuxCounters.Type type = auxType.get(ops); switch (type) { case OPERATIONS: switch (opResName) { case "ThroughputResult": case "AverageTimeResult": result.add("new " + opResName + "(ResultRole.SECONDARY, \"" + ops + "\", " + auxAccessors.get(method.getName() + ops) + ", res.getTime(), benchmarkParams.getTimeUnit())"); break; case "SampleTimeResult": case "SingleShotResult": // Not handled. break; default: throw new GenerationException("Unknown result name for @" + AuxCounters.class + ": " + opResName, method); } break; case EVENTS: result.add("new ScalarResult(\"" + ops + "\", " + auxAccessors.get(method.getName() + ops) + ", \"#\", AggregationPolicy.SUM)"); break; default: throw new GenerationException("Unknown @" + AuxCounters.class + " type: " + type, method); } } return result; } }
48,598
43.504579
196
java
jmh
jmh-master/jmh-core/src/main/java/org/openjdk/jmh/infra/BenchmarkParams.java
/* * Copyright (c) 2005, 2013, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package org.openjdk.jmh.infra; import org.openjdk.jmh.annotations.Mode; import org.openjdk.jmh.runner.WorkloadParams; import org.openjdk.jmh.runner.options.TimeValue; import org.openjdk.jmh.util.Utils; import org.openjdk.jmh.util.Version; import java.io.Serializable; import java.io.UnsupportedEncodingException; import java.net.URLEncoder; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.concurrent.TimeUnit; /** * Benchmark parameters. * * <p>{@link BenchmarkParams} handles the parameters used in the current run.</p> * <p>This class is dual-purpose:</p> * <ol> * <li>It acts as the interface between host JVM and forked JVM, so that the latter * would not have to figure out the benchmark configuration again</li> * <li>It can be injected into benchmark methods to access the runtime configuration * info about the benchmark</li> * </ol> */ public class BenchmarkParams extends BenchmarkParamsL4 { private static final long serialVersionUID = -1068219503090299117L; /** * Do the class hierarchy trick to evade false sharing, and check if it's working in runtime. * @see org.openjdk.jmh.infra.Blackhole description for the rationale */ static { Utils.check(BenchmarkParams.class, "benchmark", "generatedTarget", "synchIterations"); Utils.check(BenchmarkParams.class, "threads", "threadGroups", "forks", "warmupForks"); Utils.check(BenchmarkParams.class, "warmup", "measurement"); Utils.check(BenchmarkParams.class, "mode", "params"); Utils.check(BenchmarkParams.class, "timeUnit", "opsPerInvocation"); Utils.check(BenchmarkParams.class, "jvm", "jvmArgs"); } public BenchmarkParams(String benchmark, String generatedTarget, boolean synchIterations, int threads, int[] threadGroups, Collection<String> threadGroupLabels, int forks, int warmupForks, IterationParams warmup, IterationParams measurement, Mode mode, WorkloadParams params, TimeUnit timeUnit, int opsPerInvocation, String jvm, Collection<String> jvmArgs, String jdkVersion, String vmName, String vmVersion, String jmhVersion, TimeValue timeout) { super(benchmark, generatedTarget, synchIterations, threads, threadGroups, threadGroupLabels, forks, warmupForks, warmup, measurement, mode, params, timeUnit, opsPerInvocation, jvm, jvmArgs, jdkVersion, vmName, vmVersion, jmhVersion, timeout); } } abstract class BenchmarkParamsL4 extends BenchmarkParamsL3 { private static final long serialVersionUID = -2409216922027695385L; private int markerEnd; public BenchmarkParamsL4(String benchmark, String generatedTarget, boolean synchIterations, int threads, int[] threadGroups, Collection<String> threadGroupLabels, int forks, int warmupForks, IterationParams warmup, IterationParams measurement, Mode mode, WorkloadParams params, TimeUnit timeUnit, int opsPerInvocation, String jvm, Collection<String> jvmArgs, String jdkVersion, String vmName, String vmVersion, String jmhVersion, TimeValue timeout) { super(benchmark, generatedTarget, synchIterations, threads, threadGroups, threadGroupLabels, forks, warmupForks, warmup, measurement, mode, params, timeUnit, opsPerInvocation, jvm, jvmArgs, jdkVersion, vmName, vmVersion, jmhVersion, timeout); } } abstract class BenchmarkParamsL3 extends BenchmarkParamsL2 { private static final long serialVersionUID = -53511295235994554L; private boolean q001, q002, q003, q004, q005, q006, q007, q008; private boolean q011, q012, q013, q014, q015, q016, q017, q018; private boolean q021, q022, q023, q024, q025, q026, q027, q028; private boolean q031, q032, q033, q034, q035, q036, q037, q038; private boolean q041, q042, q043, q044, q045, q046, q047, q048; private boolean q051, q052, q053, q054, q055, q056, q057, q058; private boolean q061, q062, q063, q064, q065, q066, q067, q068; private boolean q071, q072, q073, q074, q075, q076, q077, q078; private boolean q101, q102, q103, q104, q105, q106, q107, q108; private boolean q111, q112, q113, q114, q115, q116, q117, q118; private boolean q121, q122, q123, q124, q125, q126, q127, q128; private boolean q131, q132, q133, q134, q135, q136, q137, q138; private boolean q141, q142, q143, q144, q145, q146, q147, q148; private boolean q151, q152, q153, q154, q155, q156, q157, q158; private boolean q161, q162, q163, q164, q165, q166, q167, q168; private boolean q171, q172, q173, q174, q175, q176, q177, q178; public BenchmarkParamsL3(String benchmark, String generatedTarget, boolean synchIterations, int threads, int[] threadGroups, Collection<String> threadGroupLabels, int forks, int warmupForks, IterationParams warmup, IterationParams measurement, Mode mode, WorkloadParams params, TimeUnit timeUnit, int opsPerInvocation, String jvm, Collection<String> jvmArgs, String jdkVersion, String vmName, String vmVersion, String jmhVersion, TimeValue timeout) { super(benchmark, generatedTarget, synchIterations, threads, threadGroups, threadGroupLabels, forks, warmupForks, warmup, measurement, mode, params, timeUnit, opsPerInvocation, jvm, jvmArgs, jdkVersion, vmName, vmVersion, jmhVersion, timeout); } } abstract class BenchmarkParamsL1 extends BenchmarkParamsL0 { private boolean p001, p002, p003, p004, p005, p006, p007, p008; private boolean p011, p012, p013, p014, p015, p016, p017, p018; private boolean p021, p022, p023, p024, p025, p026, p027, p028; private boolean p031, p032, p033, p034, p035, p036, p037, p038; private boolean p041, p042, p043, p044, p045, p046, p047, p048; private boolean p051, p052, p053, p054, p055, p056, p057, p058; private boolean p061, p062, p063, p064, p065, p066, p067, p068; private boolean p071, p072, p073, p074, p075, p076, p077, p078; private boolean p101, p102, p103, p104, p105, p106, p107, p108; private boolean p111, p112, p113, p114, p115, p116, p117, p118; private boolean p121, p122, p123, p124, p125, p126, p127, p128; private boolean p131, p132, p133, p134, p135, p136, p137, p138; private boolean p141, p142, p143, p144, p145, p146, p147, p148; private boolean p151, p152, p153, p154, p155, p156, p157, p158; private boolean p161, p162, p163, p164, p165, p166, p167, p168; private boolean p171, p172, p173, p174, p175, p176, p177, p178; } abstract class BenchmarkParamsL0 { private int markerBegin; } abstract class BenchmarkParamsL2 extends BenchmarkParamsL1 implements Serializable, Comparable<BenchmarkParams> { private static final long serialVersionUID = -1068219503090299117L; protected final String benchmark; protected final String generatedTarget; protected final boolean synchIterations; protected final int threads; protected final int[] threadGroups; protected final Collection<String> threadGroupLabels; protected final int forks; protected final int warmupForks; protected final IterationParams warmup; protected final IterationParams measurement; protected final Mode mode; protected final WorkloadParams params; protected final TimeUnit timeUnit; protected final int opsPerInvocation; protected final String jvm; protected final Collection<String> jvmArgs; protected final String jdkVersion; protected final String jmhVersion; protected final String vmName; protected final String vmVersion; protected final TimeValue timeout; public BenchmarkParamsL2(String benchmark, String generatedTarget, boolean synchIterations, int threads, int[] threadGroups, Collection<String> threadGroupLabels, int forks, int warmupForks, IterationParams warmup, IterationParams measurement, Mode mode, WorkloadParams params, TimeUnit timeUnit, int opsPerInvocation, String jvm, Collection<String> jvmArgs, String jdkVersion, String vmName, String vmVersion, String jmhVersion, TimeValue timeout) { this.benchmark = benchmark; this.generatedTarget = generatedTarget; this.synchIterations = synchIterations; this.threads = threads; this.threadGroups = threadGroups; this.threadGroupLabels = threadGroupLabels; this.forks = forks; this.warmupForks = warmupForks; this.warmup = warmup; this.measurement = measurement; this.mode = mode; this.params = params; this.timeUnit = timeUnit; this.opsPerInvocation = opsPerInvocation; this.jvm = jvm; this.jvmArgs = jvmArgs; this.jdkVersion = jdkVersion; this.vmName = vmName; this.vmVersion = vmVersion; this.jmhVersion = jmhVersion; this.timeout = timeout; } /** * @return how long to wait for iteration to complete */ public TimeValue getTimeout() { return timeout; } /** * @return do we synchronize iterations? */ public boolean shouldSynchIterations() { return synchIterations; } /** * @return iteration parameters for warmup phase */ public IterationParams getWarmup() { return warmup; } /** * @return iteration parameters for measurement phase */ public IterationParams getMeasurement() { return measurement; } /** * @return total measurement thread count */ public int getThreads() { return threads; } /** * @return thread distribution within the group * @see org.openjdk.jmh.runner.options.ChainedOptionsBuilder#threadGroups(int...) */ public int[] getThreadGroups() { return Arrays.copyOf(threadGroups, threadGroups.length); } /** * @return subgroup thread labels * @see #getThreadGroups() */ public Collection<String> getThreadGroupLabels() { return Collections.unmodifiableCollection(threadGroupLabels); } /** * @return number of forked VM runs, which we measure */ public int getForks() { return forks; } /** * @return number of forked VM runs, which we discard from the result */ public int getWarmupForks() { return warmupForks; } /** * @return benchmark mode */ public Mode getMode() { return mode; } /** * @return benchmark name */ public String getBenchmark() { return benchmark; } /** * @return timeUnit used in results */ public TimeUnit getTimeUnit() { return timeUnit; } /** * @return operations per invocation used */ public int getOpsPerInvocation() { return opsPerInvocation; } /** * @return all workload parameters */ public Collection<String> getParamsKeys() { return params.keys(); } /** * @param key parameter key; usually the field name * @return parameter value for given key */ public String getParam(String key) { if (params != null) { return params.get(key); } else { return null; } } /** * @return generated benchmark name */ public String generatedBenchmark() { return generatedTarget; } /** * @return JVM executable path */ public String getJvm() { return jvm; } /** * @return JMH version identical to {@link Version#getPlainVersion()}, but output format should * get there input via bean for testing purposes. */ public String getJmhVersion() { return jmhVersion; } /** * @return JVM options */ public Collection<String> getJvmArgs() { return Collections.unmodifiableCollection(jvmArgs); } /** * @return version information as returned by the effective target JVM, * via system property {@code java.version} and {@code java.vm.version} */ public String getJdkVersion() { return jdkVersion; } /** * @return version information as returned by the effective target JVM, * via system property {@code java.vm.version} */ public String getVmVersion() { return vmVersion; } /** * @return name information as returned by the effective target JVM, * via system property {@code java.vm.name} */ public String getVmName() { return vmName; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; BenchmarkParams that = (BenchmarkParams) o; if (!benchmark.equals(that.benchmark)) return false; if (mode != that.mode) return false; if (!params.equals(that.params)) return false; return true; } @Override public int hashCode() { int result = benchmark.hashCode(); result = 31 * result + mode.hashCode(); result = 31 * result + params.hashCode(); return result; } @Override public int compareTo(BenchmarkParams o) { int v = mode.compareTo(o.mode); if (v != 0) { return v; } int v1 = benchmark.compareTo(o.benchmark); if (v1 != 0) { return v1; } if (params == null || o.params == null) { return 0; } return params.compareTo(o.params); } public String id() { StringBuilder sb = new StringBuilder(); appendSanitized(sb, benchmark); sb.append("-"); sb.append(mode); for (String key : params.keys()) { sb.append("-"); appendSanitized(sb, key); sb.append("-"); appendSanitized(sb, params.get(key)); } return sb.toString(); } private static void appendSanitized(StringBuilder builder, String s) { try { builder.append(URLEncoder.encode(s, "UTF-8")); } catch (UnsupportedEncodingException e) { throw new RuntimeException(e); } } }
16,600
34.701075
113
java
jmh
jmh-master/jmh-core/src/main/java/org/openjdk/jmh/infra/Blackhole.java
/* * Copyright (c) 2005, 2013, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package org.openjdk.jmh.infra; import org.openjdk.jmh.util.Utils; import java.lang.ref.WeakReference; import java.security.AccessController; import java.security.PrivilegedAction; import java.util.Random; /* See the rationale for BlackholeL1..BlackholeL4 classes below. */ abstract class BlackholeL0 { private int markerBegin; } abstract class BlackholeL1 extends BlackholeL0 { private boolean p001, p002, p003, p004, p005, p006, p007, p008; private boolean p011, p012, p013, p014, p015, p016, p017, p018; private boolean p021, p022, p023, p024, p025, p026, p027, p028; private boolean p031, p032, p033, p034, p035, p036, p037, p038; private boolean p041, p042, p043, p044, p045, p046, p047, p048; private boolean p051, p052, p053, p054, p055, p056, p057, p058; private boolean p061, p062, p063, p064, p065, p066, p067, p068; private boolean p071, p072, p073, p074, p075, p076, p077, p078; private boolean p101, p102, p103, p104, p105, p106, p107, p108; private boolean p111, p112, p113, p114, p115, p116, p117, p118; private boolean p121, p122, p123, p124, p125, p126, p127, p128; private boolean p131, p132, p133, p134, p135, p136, p137, p138; private boolean p141, p142, p143, p144, p145, p146, p147, p148; private boolean p151, p152, p153, p154, p155, p156, p157, p158; private boolean p161, p162, p163, p164, p165, p166, p167, p168; private boolean p171, p172, p173, p174, p175, p176, p177, p178; } abstract class BlackholeL2 extends BlackholeL1 { public volatile byte b1; public volatile boolean bool1; public volatile char c1; public volatile short s1; public volatile int i1; public volatile long l1; public volatile float f1; public volatile double d1; public byte b2; public boolean bool2; public char c2; public short s2; public int i2; public long l2; public float f2; public double d2; public volatile Object obj1; public volatile BlackholeL2 nullBait = null; public int tlr; public volatile int tlrMask; public BlackholeL2() { Random r = new Random(System.nanoTime()); tlr = r.nextInt(); tlrMask = 1; obj1 = new Object(); b1 = (byte) r.nextInt(); b2 = (byte) (b1 + 1); bool1 = r.nextBoolean(); bool2 = !bool1; c1 = (char) r.nextInt(); c2 = (char) (c1 + 1); s1 = (short) r.nextInt(); s2 = (short) (s1 + 1); i1 = r.nextInt(); i2 = i1 + 1; l1 = r.nextLong(); l2 = l1 + 1; f1 = r.nextFloat(); f2 = f1 + Math.ulp(f1); d1 = r.nextDouble(); d2 = d1 + Math.ulp(d1); if (b1 == b2) { throw new IllegalStateException("byte tombstones are equal"); } if (bool1 == bool2) { throw new IllegalStateException("boolean tombstones are equal"); } if (c1 == c2) { throw new IllegalStateException("char tombstones are equal"); } if (s1 == s2) { throw new IllegalStateException("short tombstones are equal"); } if (i1 == i2) { throw new IllegalStateException("int tombstones are equal"); } if (l1 == l2) { throw new IllegalStateException("long tombstones are equal"); } if (f1 == f2) { throw new IllegalStateException("float tombstones are equal"); } if (d1 == d2) { throw new IllegalStateException("double tombstones are equal"); } } } abstract class BlackholeL3 extends BlackholeL2 { private boolean q001, q002, q003, q004, q005, q006, q007, q008; private boolean q011, q012, q013, q014, q015, q016, q017, q018; private boolean q021, q022, q023, q024, q025, q026, q027, q028; private boolean q031, q032, q033, q034, q035, q036, q037, q038; private boolean q041, q042, q043, q044, q045, q046, q047, q048; private boolean q051, q052, q053, q054, q055, q056, q057, q058; private boolean q061, q062, q063, q064, q065, q066, q067, q068; private boolean q071, q072, q073, q074, q075, q076, q077, q078; private boolean q101, q102, q103, q104, q105, q106, q107, q108; private boolean q111, q112, q113, q114, q115, q116, q117, q118; private boolean q121, q122, q123, q124, q125, q126, q127, q128; private boolean q131, q132, q133, q134, q135, q136, q137, q138; private boolean q141, q142, q143, q144, q145, q146, q147, q148; private boolean q151, q152, q153, q154, q155, q156, q157, q158; private boolean q161, q162, q163, q164, q165, q166, q167, q168; private boolean q171, q172, q173, q174, q175, q176, q177, q178; } abstract class BlackholeL4 extends BlackholeL3 { private int markerEnd; } /** * Black Hole. * * <p>Black hole "consumes" the values, conceiving no information to JIT whether the * value is actually used afterwards. This can save from the dead-code elimination * of the computations resulting in the given values.</p> */ public final class Blackhole extends BlackholeL4 { /* * IMPLEMENTATION NOTES: * * The major things to dodge with Blackholes are: * * a) Dead-code elimination: the arguments should be used on every call, * so that compilers are unable to fold them into constants or * otherwise optimize them away along with the computations resulted * in them. * * b) False sharing: reading/writing the state may disturb the cache * lines. We need to isolate the critical fields to achieve tolerable * performance. * * c) Write wall: we need to ease off on writes as much as possible, * since it disturbs the caches, pollutes the write buffers, etc. * This may very well result in hitting the memory wall prematurely. * Reading memory is fine as long as it is cacheable. * * To achieve these goals, we are piggybacking on several things in the * compilers: * * 1. Superclass fields are not reordered with the subclass' fields. * No practical VM that we are aware of is doing this. It is unpractical, * because if the superclass fields are at the different offsets in two * subclasses, the VMs would then need to do the polymorphic access for * the superclass fields. * * 2. Compilers are unable to predict the value of the volatile read. * While the compilers can speculatively optimize until the relevant * volatile write happens, it is unlikely to be practical to be able to stop * all the threads the instant that write had happened. * * 3. Compilers' code motion usually respects data dependencies, and they would * not normally schedule the consumer block before the code that generated * a value. * * 4. Compilers are not doing aggressive inter-procedural optimizations, * and/or break them when the target method is forced to be non-inlineable. * * Observation (1) allows us to "squash" the protected fields in the inheritance * hierarchy so that the padding in super- and sub-class are laid out right before * and right after the protected fields. We also pad with booleans so that dense * layout in superclass does not have the gap where runtime can fit the subclass field. * * Observation (2) allows us to compare the incoming primitive values against * the relevant volatile-guarded fields. The values in those guarded fields are * never changing, but due to (2), we should re-read the values again and again. * Also, observation (3) requires us to to use the incoming value in the computation, * thus anchoring the Blackhole code after the generating expression. * * Primitives are a bit hard, because we can't predict what values we * will be fed. But we can compare the incoming value with *two* distinct * known values, and both checks will never be true at the same time. * Note the bitwise AND in all the predicates: both to spare additional * branch, and also to provide more uniformity in the performance. Where possible, * we are using a specific code shape to force generating a single branch, e.g. * making compiler to evaluate the predicate in full, not speculate on components. * * Objects should normally abide the Java's referential semantics, i.e. the * incoming objects will never be equal to the distinct object we have, and * volatile read will break the speculation about what we compare with. * However, smart compilers may deduce that the distinct non-escaped object * on the other side is not equal to anything we have, and fold the comparison * to "false". We do inlined thread-local random to get those objects escaped * with infinitesimal probability. Then again, smart compilers may skip from * generating the slow path, and apply the previous logic to constant-fold * the condition to "false". We are warming up the slow-path in the beginning * to evade that effect. Some caution needs to be exercised not to retain the * captured objects forever: this is normally achieved by calling evaporate() * regularly, but we also additionally protect with retaining the object on * weak reference (contrary to phantom-ref, publishing object still has to * happen, because reference users might need to discover the object). * * Observation (4) provides us with an opportunity to create a safety net in case * either (1), (2) or (3) fails. This is why Blackhole methods are prohibited from * being inlined. This is treated specially in JMH runner code (see CompilerHints). * Conversely, both (1), (2), (3) are covering in case (4) fails. This provides * a defense in depth for Blackhole implementation, where a point failure is a * performance nuisance, but not a correctness catastrophe. * * In all cases, consumes do the volatile reads to have a consistent memory * semantics across all consume methods. * * There is an experimental compiler support for Blackholes that instructs compilers * to treat specific methods as blackholes: keeping their arguments alive. At some * point in the future, we hope to switch to that mode by default, thus greatly * simplifying the Blackhole code. * * An utmost caution should be exercised when changing the Blackhole code. Nominally, * the JMH Core Benchmarks should be run on multiple platforms (and their generated code * examined) to check the effects are still in place, and the overheads are not prohibitive. * Or, in other words: * * IMPLEMENTING AN EFFICIENT / CORRECT BLACKHOLE IS NOT A SIMPLE TASK YOU CAN * DO OVERNIGHT. IT REQUIRES A SIGNIFICANT JVM/COMPILER/PERFORMANCE EXPERTISE, * AND LOTS OF TIME OVER THAT. ADJUST YOUR PLANS ACCORDINGLY. */ private static final boolean COMPILER_BLACKHOLE; static { COMPILER_BLACKHOLE = AccessController.doPrivileged(new PrivilegedAction<Boolean>() { public Boolean run() { return Boolean.getBoolean("compilerBlackholesEnabled"); } }); Utils.check(Blackhole.class, "b1", "b2"); Utils.check(Blackhole.class, "bool1", "bool2"); Utils.check(Blackhole.class, "c1", "c2"); Utils.check(Blackhole.class, "s1", "s2"); Utils.check(Blackhole.class, "i1", "i2"); Utils.check(Blackhole.class, "l1", "l2"); Utils.check(Blackhole.class, "f1", "f2"); Utils.check(Blackhole.class, "d1", "d2"); Utils.check(Blackhole.class, "obj1"); } public Blackhole(String challengeResponse) { /* * Prevent instantiation by user code. Without additional countermeasures * to properly escape Blackhole, its magic is not working. The instances * of Blackholes which are injected into benchmark methods are treated by JMH, * and users are supposed to only use the injected instances. * * It only *seems* simple to make the constructor non-public, but then * there is a lot of infrastructure code which assumes @State has a default * constructor. One might suggest doing the internal factory method to instantiate, * but that does not help when extending the Blackhole. There is a *messy* way to * special-case most of these problems within the JMH code, but it does not seem * to worth the effort. * * Therefore, we choose to fail at runtime. It will only affect the users who thought * "new Blackhole()" is a good idea, and these users are rare. If you are reading this * comment, you might be one of those users. Stay cool! Don't instantiate Blackholes * directly though. */ if (!challengeResponse.equals("Today's password is swordfish. I understand instantiating Blackholes directly is dangerous.")) { throw new IllegalStateException("Blackholes should not be instantiated directly."); } } /** * Make any consumed data begone. * * WARNING: This method should only be called by the infrastructure code, in clearly understood cases. * Even though it is public, it is not supposed to be called by users. * * @param challengeResponse arbitrary string */ public void evaporate(String challengeResponse) { if (!challengeResponse.equals("Yes, I am Stephen Hawking, and know a thing or two about black holes.")) { throw new IllegalStateException("Who are you?"); } obj1 = null; } /** * Consume object. This call provides a side effect preventing JIT to eliminate dependent computations. * * @param obj object to consume. */ public final void consume(Object obj) { if (COMPILER_BLACKHOLE) { consumeCompiler(obj); } else { consumeFull(obj); } } /** * Consume object. This call provides a side effect preventing JIT to eliminate dependent computations. * * @param b object to consume. */ public final void consume(byte b) { if (COMPILER_BLACKHOLE) { consumeCompiler(b); } else { consumeFull(b); } } /** * Consume object. This call provides a side effect preventing JIT to eliminate dependent computations. * * @param bool object to consume. */ public final void consume(boolean bool) { if (COMPILER_BLACKHOLE) { consumeCompiler(bool); } else { consumeFull(bool); } } /** * Consume object. This call provides a side effect preventing JIT to eliminate dependent computations. * * @param c object to consume. */ public final void consume(char c) { if (COMPILER_BLACKHOLE) { consumeCompiler(c); } else { consumeFull(c); } } /** * Consume object. This call provides a side effect preventing JIT to eliminate dependent computations. * * @param s object to consume. */ public final void consume(short s) { if (COMPILER_BLACKHOLE) { consumeCompiler(s); } else { consumeFull(s); } } /** * Consume object. This call provides a side effect preventing JIT to eliminate dependent computations. * * @param i object to consume. */ public final void consume(int i) { if (COMPILER_BLACKHOLE) { consumeCompiler(i); } else { consumeFull(i); } } /** * Consume object. This call provides a side effect preventing JIT to eliminate dependent computations. * * @param l object to consume. */ public final void consume(long l) { if (COMPILER_BLACKHOLE) { consumeCompiler(l); } else { consumeFull(l); } } /** * Consume object. This call provides a side effect preventing JIT to eliminate dependent computations. * * @param f object to consume. */ public final void consume(float f) { if (COMPILER_BLACKHOLE) { consumeCompiler(f); } else { consumeFull(f); } } /** * Consume object. This call provides a side effect preventing JIT to eliminate dependent computations. * * @param d object to consume. */ public final void consume(double d) { if (COMPILER_BLACKHOLE) { consumeCompiler(d); } else { consumeFull(d); } } // Compiler blackholes block: let compilers figure out how to deal with it. private static void consumeCompiler(boolean v) {} private static void consumeCompiler(byte v) {} private static void consumeCompiler(short v) {} private static void consumeCompiler(char v) {} private static void consumeCompiler(int v) {} private static void consumeCompiler(float v) {} private static void consumeCompiler(double v) {} private static void consumeCompiler(long v) {} private static void consumeCompiler(Object v) {} // Full blackholes block: confuse compilers to get blackholing effects. // See implementation comments at the top to understand what this code is doing. private void consumeFull(byte b) { byte b1 = this.b1; // volatile read byte b2 = this.b2; if ((b ^ b1) == (b ^ b2)) { // SHOULD NEVER HAPPEN nullBait.b1 = b; // implicit null pointer exception } } private void consumeFull(boolean bool) { boolean bool1 = this.bool1; // volatile read boolean bool2 = this.bool2; if ((bool ^ bool1) == (bool ^ bool2)) { // SHOULD NEVER HAPPEN nullBait.bool1 = bool; // implicit null pointer exception } } private void consumeFull(char c) { char c1 = this.c1; // volatile read char c2 = this.c2; if ((c ^ c1) == (c ^ c2)) { // SHOULD NEVER HAPPEN nullBait.c1 = c; // implicit null pointer exception } } private void consumeFull(short s) { short s1 = this.s1; // volatile read short s2 = this.s2; if ((s ^ s1) == (s ^ s2)) { // SHOULD NEVER HAPPEN nullBait.s1 = s; // implicit null pointer exception } } private void consumeFull(int i) { int i1 = this.i1; // volatile read int i2 = this.i2; if ((i ^ i1) == (i ^ i2)) { // SHOULD NEVER HAPPEN nullBait.i1 = i; // implicit null pointer exception } } private void consumeFull(long l) { long l1 = this.l1; // volatile read long l2 = this.l2; if ((l ^ l1) == (l ^ l2)) { // SHOULD NEVER HAPPEN nullBait.l1 = l; // implicit null pointer exception } } private void consumeFull(float f) { float f1 = this.f1; // volatile read float f2 = this.f2; if (f == f1 & f == f2) { // SHOULD NEVER HAPPEN nullBait.f1 = f; // implicit null pointer exception } } private void consumeFull(double d) { double d1 = this.d1; // volatile read double d2 = this.d2; if (d == d1 & d == d2) { // SHOULD NEVER HAPPEN nullBait.d1 = d; // implicit null pointer exception } } private void consumeFull(Object obj) { int tlrMask = this.tlrMask; // volatile read int tlr = (this.tlr = (this.tlr * 1664525 + 1013904223)); if ((tlr & tlrMask) == 0) { // SHOULD ALMOST NEVER HAPPEN IN MEASUREMENT this.obj1 = new WeakReference<>(obj); this.tlrMask = (tlrMask << 1) + 1; } } private static volatile long consumedCPU = System.nanoTime(); /** * Consume some amount of time tokens. * * This method does the CPU work almost linear to the number of tokens. * The token cost may vary from system to system, and may change in * future. (Translation: it is as reliable as we can get, but not absolutely * reliable). * * See JMH samples for the complete demo, and core benchmarks for * the performance assessments. * * @param tokens CPU tokens to consume */ public static void consumeCPU(long tokens) { // If you are looking at this code trying to understand // the non-linearity on low token counts, know this: // we are pretty sure the generated assembly for almost all // cases is the same, and the only explanation for the // performance difference is hardware-specific effects. // Be wary to waste more time on this. If you know more // advanced and clever option to implement consumeCPU, let us // know. // Randomize start so that JIT could not memoize; this helps // to break the loop optimizations if the method is called // from the external loop body. long t = consumedCPU; // One of the rare cases when counting backwards is meaningful: // for the forward loop HotSpot/x86 generates "cmp" with immediate // on the hot path, while the backward loop tests against zero // with "test". The immediate can have different lengths, which // attribute to different machine code for different cases. We // counter that with always counting backwards. We also mix the // induction variable in, so that reversing the loop is the // non-trivial optimization. for (long i = tokens; i > 0; i--) { t += (t * 0x5DEECE66DL + 0xBL + i) & (0xFFFFFFFFFFFFL); } // Need to guarantee side-effect on the result, but can't afford // contention; make sure we update the shared state only in the // unlikely case, so not to do the furious writes, but still // dodge DCE. if (t == 42) { consumedCPU += t; } } }
23,467
39.323024
135
java
jmh
jmh-master/jmh-core/src/main/java/org/openjdk/jmh/infra/Control.java
/* * Copyright (c) 2005, 2013, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package org.openjdk.jmh.infra; import org.openjdk.jmh.util.Utils; /** * Control object, used to communicate significant information from JMH to the benchmark. * WARNING: The API for this class is considered unstable, and can be changed without notice. */ public final class Control extends ControlL4 { /** * Do the class hierarchy trick to evade false sharing, and check if it's working in runtime. * @see org.openjdk.jmh.infra.Blackhole description for the rationale */ static { Utils.check(Control.class, "startMeasurement", "stopMeasurement"); } } abstract class ControlL0 { private int markerBegin; } abstract class ControlL1 extends ControlL0 { private boolean p001, p002, p003, p004, p005, p006, p007, p008; private boolean p011, p012, p013, p014, p015, p016, p017, p018; private boolean p021, p022, p023, p024, p025, p026, p027, p028; private boolean p031, p032, p033, p034, p035, p036, p037, p038; private boolean p041, p042, p043, p044, p045, p046, p047, p048; private boolean p051, p052, p053, p054, p055, p056, p057, p058; private boolean p061, p062, p063, p064, p065, p066, p067, p068; private boolean p071, p072, p073, p074, p075, p076, p077, p078; private boolean p101, p102, p103, p104, p105, p106, p107, p108; private boolean p111, p112, p113, p114, p115, p116, p117, p118; private boolean p121, p122, p123, p124, p125, p126, p127, p128; private boolean p131, p132, p133, p134, p135, p136, p137, p138; private boolean p141, p142, p143, p144, p145, p146, p147, p148; private boolean p151, p152, p153, p154, p155, p156, p157, p158; private boolean p161, p162, p163, p164, p165, p166, p167, p168; private boolean p171, p172, p173, p174, p175, p176, p177, p178; } abstract class ControlL2 extends ControlL1 { /** * Transitions to "true", once JMH had started the measurement for the current iteration. */ public volatile boolean startMeasurement; /** * Transitions to "true", once JMH is stopping the measurement for the current iteration */ public volatile boolean stopMeasurement; } abstract class ControlL3 extends ControlL2 { private boolean q001, q002, q003, q004, q005, q006, q007, q008; private boolean q011, q012, q013, q014, q015, q016, q017, q018; private boolean q021, q022, q023, q024, q025, q026, q027, q028; private boolean q031, q032, q033, q034, q035, q036, q037, q038; private boolean q041, q042, q043, q044, q045, q046, q047, q048; private boolean q051, q052, q053, q054, q055, q056, q057, q058; private boolean q061, q062, q063, q064, q065, q066, q067, q068; private boolean q071, q072, q073, q074, q075, q076, q077, q078; private boolean q101, q102, q103, q104, q105, q106, q107, q108; private boolean q111, q112, q113, q114, q115, q116, q117, q118; private boolean q121, q122, q123, q124, q125, q126, q127, q128; private boolean q131, q132, q133, q134, q135, q136, q137, q138; private boolean q141, q142, q143, q144, q145, q146, q147, q148; private boolean q151, q152, q153, q154, q155, q156, q157, q158; private boolean q161, q162, q163, q164, q165, q166, q167, q168; private boolean q171, q172, q173, q174, q175, q176, q177, q178; } abstract class ControlL4 extends ControlL3 { private int markerEnd; }
4,574
42.571429
97
java
jmh
jmh-master/jmh-core/src/main/java/org/openjdk/jmh/infra/IterationParams.java
/* * Copyright (c) 2005, 2013, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package org.openjdk.jmh.infra; import org.openjdk.jmh.runner.IterationType; import org.openjdk.jmh.runner.options.TimeValue; import org.openjdk.jmh.util.Utils; import java.io.Serializable; import java.util.Objects; /** * Iteration parameters. * * <p>Iteration parameters are separated in at least two instances, with different {@link IterationType}-s. * The complete benchmark parameters not specific for a particular iteration are available in * {@link org.openjdk.jmh.infra.BenchmarkParams}.</p> * <p>This class is dual-purpose:</p> * <ol> * <li>It acts as the interface between host JVM and forked JVM, so that the latter * would not have to figure out the benchmark configuration again</li> * <li>It can be injected into benchmark methods to access the runtime configuration * info about the benchmark</li> * </ol> */ public final class IterationParams extends IterationParamsL4 { private static final long serialVersionUID = -8111111319033802892L; static { Utils.check(IterationParams.class, "type", "count", "timeValue", "batchSize"); } public IterationParams(IterationType type, int count, TimeValue time, int batchSize) { super(type, count, time, batchSize); } } abstract class IterationParamsL4 extends IterationParamsL3 { private static final long serialVersionUID = 9079354621906758255L; private int markerEnd; public IterationParamsL4(IterationType type, int count, TimeValue time, int batchSize) { super(type, count, time, batchSize); } } abstract class IterationParamsL3 extends IterationParamsL2 { private static final long serialVersionUID = 3907464940104879178L; private boolean q001, q002, q003, q004, q005, q006, q007, q008; private boolean q011, q012, q013, q014, q015, q016, q017, q018; private boolean q021, q022, q023, q024, q025, q026, q027, q028; private boolean q031, q032, q033, q034, q035, q036, q037, q038; private boolean q041, q042, q043, q044, q045, q046, q047, q048; private boolean q051, q052, q053, q054, q055, q056, q057, q058; private boolean q061, q062, q063, q064, q065, q066, q067, q068; private boolean q071, q072, q073, q074, q075, q076, q077, q078; private boolean q101, q102, q103, q104, q105, q106, q107, q108; private boolean q111, q112, q113, q114, q115, q116, q117, q118; private boolean q121, q122, q123, q124, q125, q126, q127, q128; private boolean q131, q132, q133, q134, q135, q136, q137, q138; private boolean q141, q142, q143, q144, q145, q146, q147, q148; private boolean q151, q152, q153, q154, q155, q156, q157, q158; private boolean q161, q162, q163, q164, q165, q166, q167, q168; private boolean q171, q172, q173, q174, q175, q176, q177, q178; public IterationParamsL3(IterationType type, int count, TimeValue time, int batchSize) { super(type, count, time, batchSize); } } abstract class IterationParamsL1 extends IterationParamsL0 { private boolean p001, p002, p003, p004, p005, p006, p007, p008; private boolean p011, p012, p013, p014, p015, p016, p017, p018; private boolean p021, p022, p023, p024, p025, p026, p027, p028; private boolean p031, p032, p033, p034, p035, p036, p037, p038; private boolean p041, p042, p043, p044, p045, p046, p047, p048; private boolean p051, p052, p053, p054, p055, p056, p057, p058; private boolean p061, p062, p063, p064, p065, p066, p067, p068; private boolean p071, p072, p073, p074, p075, p076, p077, p078; private boolean p101, p102, p103, p104, p105, p106, p107, p108; private boolean p111, p112, p113, p114, p115, p116, p117, p118; private boolean p121, p122, p123, p124, p125, p126, p127, p128; private boolean p131, p132, p133, p134, p135, p136, p137, p138; private boolean p141, p142, p143, p144, p145, p146, p147, p148; private boolean p151, p152, p153, p154, p155, p156, p157, p158; private boolean p161, p162, p163, p164, p165, p166, p167, p168; private boolean p171, p172, p173, p174, p175, p176, p177, p178; } abstract class IterationParamsL0 { private int markerBegin; } abstract class IterationParamsL2 extends IterationParamsL1 implements Serializable { private static final long serialVersionUID = -6138850517953881052L; /** * iteration type */ protected final IterationType type; /** * amount of iterations */ protected final int count; /** * iteration runtime */ protected final TimeValue timeValue; /** * batch size (method invocations inside the single op) */ protected final int batchSize; public IterationParamsL2(IterationType type, int count, TimeValue time, int batchSize) { this.type = type; this.count = count; this.timeValue = time; this.batchSize = batchSize; } /** * Iteration type: separates warmup iterations vs. measurement iterations. * @return iteration type. */ public IterationType getType() { return type; } /** * Number of iterations. * @return number of iterations of given type. */ public int getCount() { return count; } /** * Time for iteration. * @return time */ public TimeValue getTime() { return timeValue; } /** * Batch size for iteration. * @return batch size */ public int getBatchSize() { return batchSize; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; IterationParams that = (IterationParams) o; if (count != that.count) return false; if (batchSize != that.batchSize) return false; if (!Objects.equals(timeValue, that.timeValue)) return false; return true; } @Override public int hashCode() { int result = count; result = 31 * result + batchSize; result = 31 * result + (timeValue != null ? timeValue.hashCode() : 0); return result; } @Override public String toString() { return "IterationParams("+ getCount()+", "+ getTime()+", "+ getBatchSize()+")"; } }
7,465
35.067633
107
java
jmh
jmh-master/jmh-core/src/main/java/org/openjdk/jmh/infra/ThreadParams.java
/* * Copyright (c) 2005, 2013, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package org.openjdk.jmh.infra; import org.openjdk.jmh.util.Utils; /** * Thread parameters. * * <p>Thread parameters handle the infrastructure info about the threading, including but * not limited to the number of threads, thread indicies, group information, etc. Some * of that info duplicates what is available in {@link org.openjdk.jmh.infra.BenchmarkParams}.</p> */ public final class ThreadParams extends ThreadParamsL4 { public ThreadParams(int threadIdx, int threadCount, int groupIdx, int groupCount, int subgroupIdx, int subgroupCount, int groupThreadIdx, int groupThreadCount, int subgroupThreadIdx, int subgroupThreadCount) { super(threadIdx, threadCount, groupIdx, groupCount, subgroupIdx, subgroupCount, groupThreadIdx, groupThreadCount, subgroupThreadIdx, subgroupThreadCount); } static { Utils.check(ThreadParams.class, "threadIdx", "threadCount"); Utils.check(ThreadParams.class, "groupIdx", "groupCount"); Utils.check(ThreadParams.class, "subgroupIdx", "subgroupCount"); Utils.check(ThreadParams.class, "groupThreadIdx", "groupThreadCount"); Utils.check(ThreadParams.class, "subgroupThreadIdx", "subgroupThreadCount"); } /** * Answers the number of groups in the run. * * <p>When running the symmetric benchmark, each thread occupies its own group, * and therefore number of groups equals the thread count.</p> * * <p>This is a convenience method, similar info can be figured out by dividing * the number of threads ({@link #getThreadCount()}) by the number of threads per * group ({@link #getGroupThreadCount()}).</p> * * @return number of groups * @see #getThreadCount() */ public int getGroupCount() { return groupCount; } /** * Answers the thread group index. * * <p>Group indices are having the range of [0..G-1], where G is the number * of thread groups in the run. When running the symmetric benchmark, each * thread occupies its own group, and therefore the group index equals to * the thread index.</p> * * @return thread group index * @see #getGroupCount() */ public int getGroupIndex() { return groupIdx; } /** * Answers the number of distinct workloads (subgroups) in the current group. * * <p>When running the symmetric benchmark, each thread occupies its own group, * and therefore number of subgroups equals to one.</p> * * @return number of subgroups * @see #getThreadCount() */ public int getSubgroupCount() { return subgroupCount; } /** * Answers the subgroup index. * * <p>Subgroup index enumerates the distinct workloads (subgroups) in current * group. The index the range of [0..S-1], where S is the number of subgroups * in current group. When running the symmetric benchmark, there is only * a single workload in the group, and therefore the subgroup index is zero.</p> * * @return subgroup index * @see #getSubgroupCount() */ public int getSubgroupIndex() { return subgroupIdx; } /** * Answers the number of threads participating in the run. * * <p>This is a convenience method, similar info can be queried directly from * {@link org.openjdk.jmh.infra.BenchmarkParams#getThreads()}</p> * * @return number of threads */ public int getThreadCount() { return threadCount; } /** * Answers the thread index. * * <p>Thread indices are in range [0..N-1], where N is the number of threads * participating in the run.</p> * * @return thread index * @see #getThreadCount() */ public int getThreadIndex() { return threadIdx; } /** * Answers the number of threads in the current group. * * <p>When running the symmetric benchmark, each thread occupies its own group, * and therefore number of subgroups equals to one.</p> * * <p>This is a convenience method, similar info can be figured out by summing * up the thread distribution from * {@link org.openjdk.jmh.infra.BenchmarkParams#getThreadGroups()}.</p> * * @return number of threads in the group * @see #getThreadCount() */ public int getGroupThreadCount() { return groupThreadCount; } /** * Answers the thread sub-index in current group. * * <p>Subgroup index enumerates the thread within a group, and takes * the range of [0..T-1], where T is the number of threads in current * group. When running the symmetric benchmark, each thread occupies * its own group, and therefore the subgroup index is zero.</p> * * @return index of thread in the group * @see #getGroupThreadCount() */ public int getGroupThreadIndex() { return groupThreadIdx; } /** * Answers the number of threads in the current subgroup. * * <p>When running the symmetric benchmark, each thread occupies its own group, * each thread implicitly occupies a single subgroup, and therefore, the number * of subgroups equals to one.</p> * * <p>This is a convenience method, similar info can be figured out with * querying {@link org.openjdk.jmh.infra.BenchmarkParams#getThreadGroups()} with * {@link #getSubgroupIndex()} used as index.</p> * * @return number of threads in subgroup * @see #getThreadCount() */ public int getSubgroupThreadCount() { return subgroupThreadCount; } /** * Answers the thread sub-index in current subgroup. * * <p>Subgroup index enumerates the thread within a subgroup, and takes * the range of [0..T-1], where T is the number of threads in current * subgroup. When running the symmetric benchmark, each thread occupies * its own group, and therefore the subgroup index is zero.</p> * * @return index of thread in subgroup * @see #getSubgroupThreadCount() */ public int getSubgroupThreadIndex() { return subgroupThreadIdx; } } abstract class ThreadParamsL0 { private int markerBegin; } abstract class ThreadParamsL1 extends ThreadParamsL0 { private boolean p001, p002, p003, p004, p005, p006, p007, p008; private boolean p011, p012, p013, p014, p015, p016, p017, p018; private boolean p021, p022, p023, p024, p025, p026, p027, p028; private boolean p031, p032, p033, p034, p035, p036, p037, p038; private boolean p041, p042, p043, p044, p045, p046, p047, p048; private boolean p051, p052, p053, p054, p055, p056, p057, p058; private boolean p061, p062, p063, p064, p065, p066, p067, p068; private boolean p071, p072, p073, p074, p075, p076, p077, p078; private boolean p101, p102, p103, p104, p105, p106, p107, p108; private boolean p111, p112, p113, p114, p115, p116, p117, p118; private boolean p121, p122, p123, p124, p125, p126, p127, p128; private boolean p131, p132, p133, p134, p135, p136, p137, p138; private boolean p141, p142, p143, p144, p145, p146, p147, p148; private boolean p151, p152, p153, p154, p155, p156, p157, p158; private boolean p161, p162, p163, p164, p165, p166, p167, p168; private boolean p171, p172, p173, p174, p175, p176, p177, p178; } abstract class ThreadParamsL2 extends ThreadParamsL1 { protected final int threadIdx, threadCount; protected final int groupIdx, groupCount; protected final int subgroupIdx, subgroupCount; protected final int groupThreadIdx, groupThreadCount; protected final int subgroupThreadIdx, subgroupThreadCount; public ThreadParamsL2(int threadIdx, int threadCount, int groupIdx, int groupCount, int subgroupIdx, int subgroupCount, int groupThreadIdx, int groupThreadCount, int subgroupThreadIdx, int subgroupThreadCount) { this.threadIdx = threadIdx; this.threadCount = threadCount; this.groupIdx = groupIdx; this.groupCount = groupCount; this.subgroupIdx = subgroupIdx; this.subgroupCount = subgroupCount; this.groupThreadIdx = groupThreadIdx; this.groupThreadCount = groupThreadCount; this.subgroupThreadIdx = subgroupThreadIdx; this.subgroupThreadCount = subgroupThreadCount; } } abstract class ThreadParamsL3 extends ThreadParamsL2 { private boolean q001, q002, q003, q004, q005, q006, q007, q008; private boolean q011, q012, q013, q014, q015, q016, q017, q018; private boolean q021, q022, q023, q024, q025, q026, q027, q028; private boolean q031, q032, q033, q034, q035, q036, q037, q038; private boolean q041, q042, q043, q044, q045, q046, q047, q048; private boolean q051, q052, q053, q054, q055, q056, q057, q058; private boolean q061, q062, q063, q064, q065, q066, q067, q068; private boolean q071, q072, q073, q074, q075, q076, q077, q078; private boolean q101, q102, q103, q104, q105, q106, q107, q108; private boolean q111, q112, q113, q114, q115, q116, q117, q118; private boolean q121, q122, q123, q124, q125, q126, q127, q128; private boolean q131, q132, q133, q134, q135, q136, q137, q138; private boolean q141, q142, q143, q144, q145, q146, q147, q148; private boolean q151, q152, q153, q154, q155, q156, q157, q158; private boolean q161, q162, q163, q164, q165, q166, q167, q168; private boolean q171, q172, q173, q174, q175, q176, q177, q178; public ThreadParamsL3(int threadIdx, int threadCount, int groupIdx, int groupCount, int subgroupIdx, int subgroupCount, int groupThreadIdx, int groupThreadCount, int subgroupThreadIdx, int subgroupThreadCount) { super(threadIdx, threadCount, groupIdx, groupCount, subgroupIdx, subgroupCount, groupThreadIdx, groupThreadCount, subgroupThreadIdx, subgroupThreadCount); } } abstract class ThreadParamsL4 extends ThreadParamsL3 { private int markerEnd; public ThreadParamsL4(int threadIdx, int threadCount, int groupIdx, int groupCount, int subgroupIdx, int subgroupCount, int groupThreadIdx, int groupThreadCount, int subgroupThreadIdx, int subgroupThreadCount) { super(threadIdx, threadCount, groupIdx, groupCount, subgroupIdx, subgroupCount, groupThreadIdx, groupThreadCount, subgroupThreadIdx, subgroupThreadCount); } }
11,742
40.641844
123
java
jmh
jmh-master/jmh-core/src/main/java/org/openjdk/jmh/profile/AbstractPerfAsmProfiler.java
/* * Copyright (c) 2014, 2014, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package org.openjdk.jmh.profile; import joptsimple.OptionException; import joptsimple.OptionParser; import joptsimple.OptionSet; import joptsimple.OptionSpec; import org.openjdk.jmh.infra.BenchmarkParams; import org.openjdk.jmh.results.*; import org.openjdk.jmh.util.*; import java.io.*; import java.util.*; import java.util.regex.Matcher; import java.util.regex.Pattern; public abstract class AbstractPerfAsmProfiler implements ExternalProfiler { protected final List<String> requestedEventNames; private final double regionRateThreshold; private final int regionShowTop; private final int regionTooBigThreshold; private final int printMargin; private final int mergeMargin; private final boolean mergeMethods; private final int delayMsec; private final int lengthMsec; private final boolean skipAssembly; private final boolean skipInterpreter; private final boolean skipVMStubs; private final boolean savePerfOutput; private final String savePerfOutputTo; private final String savePerfOutputToFile; private final boolean savePerfBin; private final String savePerfBinTo; private final String savePerfBinFile; private final boolean saveLog; private final String saveLogTo; private final String saveLogToFile; private final boolean intelSyntax; protected final TempFile hsLog; protected final TempFile perfBinData; protected final TempFile perfParsedData; protected final OptionSet set; private final boolean drawIntraJumps; private final boolean drawInterJumps; private final ShowCounts showCounts; private enum ShowCounts { raw, norm, percent_total, } protected AbstractPerfAsmProfiler(String initLine, String... events) throws ProfilerException { try { hsLog = FileUtils.weakTempFile("hslog"); perfBinData = FileUtils.weakTempFile("perfbin"); perfParsedData = FileUtils.weakTempFile("perfparsed"); } catch (IOException e) { throw new ProfilerException(e); } OptionParser parser = new OptionParser(); parser.formatHelpWith(new ProfilerOptionFormatter("perfasm")); OptionSpec<String> optEvents = parser.accepts("events", "Events to gather.") .withRequiredArg().ofType(String.class).withValuesSeparatedBy(",").describedAs("event").defaultsTo(events); OptionSpec<Double> optThresholdRate = parser.accepts("hotThreshold", "Cutoff threshold for hot regions. The regions with event count over threshold would be expanded " + "with detailed disassembly.") .withRequiredArg().ofType(Double.class).describedAs("rate").defaultsTo(0.10); OptionSpec<Integer> optShowTop = parser.accepts("top", "Show this number of top hottest code regions.") .withRequiredArg().ofType(Integer.class).describedAs("#").defaultsTo(20); OptionSpec<Integer> optThreshold = parser.accepts("tooBigThreshold", "Cutoff threshold for large region. The region containing more than this number of lines " + "would be truncated.") .withRequiredArg().ofType(Integer.class).describedAs("lines").defaultsTo(1000); OptionSpec<Integer> optPrintMargin = parser.accepts("printMargin", "Print margin. How many \"context\" lines without counters to show in each region.") .withRequiredArg().ofType(Integer.class).describedAs("lines").defaultsTo(10); OptionSpec<Integer> optMergeMargin = parser.accepts("mergeMargin", "Merge margin. The regions separated by less than the margin are merged.") .withRequiredArg().ofType(Integer.class).describedAs("lines").defaultsTo(32); OptionSpec<Boolean> optMergeMethods = parser.accepts("mergeMethods", "Merge all regions from the same method") .withRequiredArg().ofType(Boolean.class).describedAs("bool").defaultsTo(false); OptionSpec<Integer> optDelay = parser.accepts("delay", "Delay collection for a given time, in milliseconds; -1 to detect automatically.") .withRequiredArg().ofType(Integer.class).describedAs("ms").defaultsTo(-1); OptionSpec<Integer> optLength = parser.accepts("length", "Do the collection for a given time, in milliseconds; -1 to detect automatically.") .withRequiredArg().ofType(Integer.class).describedAs("ms").defaultsTo(-1); OptionSpec<Boolean> optSkipAsm = parser.accepts("skipAsm", "Skip -XX:+PrintAssembly instrumentation.") .withRequiredArg().ofType(Boolean.class).describedAs("bool").defaultsTo(false); OptionSpec<Boolean> optSkipInterpreter = parser.accepts("skipInterpreter", "Skip printing out interpreter stubs. This may improve the parser performance at the expense " + "of missing the resolution and disassembly of interpreter regions.") .withRequiredArg().ofType(Boolean.class).describedAs("bool").defaultsTo(false); OptionSpec<Boolean> optSkipVMStubs = parser.accepts("skipVMStubs", "Skip printing out VM stubs. This may improve the parser performance at the expense " + "of missing the resolution and disassembly of VM stub regions.") .withRequiredArg().ofType(Boolean.class).describedAs("bool").defaultsTo(false); OptionSpec<Boolean> optPerfOut = parser.accepts("savePerf", "Save parsed perf output to file. Use this for debugging.") .withRequiredArg().ofType(Boolean.class).describedAs("bool").defaultsTo(false); OptionSpec<String> optPerfOutTo = parser.accepts("savePerfTo", "Override the parsed perf output log location. This will use the unique file name per test. Use this for debugging.") .withRequiredArg().ofType(String.class).describedAs("dir").defaultsTo("."); OptionSpec<String> optPerfOutToFile = parser.accepts("savePerfToFile", "Override the perf output log filename. Use this for debugging.") .withRequiredArg().ofType(String.class).describedAs("file"); OptionSpec<Boolean> optPerfBin = parser.accepts("savePerfBin", "Save binary perf data to file. Use this for debugging.") .withRequiredArg().ofType(Boolean.class).describedAs("bool").defaultsTo(false); OptionSpec<String> optPerfBinTo = parser.accepts("savePerfBinTo", "Override the binary perf data location. This will use the unique file name per test. Use this for debugging.") .withRequiredArg().ofType(String.class).describedAs("dir").defaultsTo("."); OptionSpec<String> optPerfBinToFile = parser.accepts("savePerfBinToFile", "Override the perf binary data filename. Use this for debugging.") .withRequiredArg().ofType(String.class).describedAs("file"); OptionSpec<Boolean> optSaveLog = parser.accepts("saveLog", "Save annotated Hotspot log to file.") .withRequiredArg().ofType(Boolean.class).describedAs("bool").defaultsTo(false); OptionSpec<String> optSaveLogTo = parser.accepts("saveLogTo", "Override the annotated Hotspot log location. This will use the unique file name per test.") .withRequiredArg().ofType(String.class).describedAs("dir").defaultsTo("."); OptionSpec<String> optSaveLogToFile = parser.accepts("saveLogToFile", "Override the annotated Hotspot log filename.") .withRequiredArg().ofType(String.class).describedAs("file"); OptionSpec<Boolean> optIntelSyntax = parser.accepts("intelSyntax", "Should perfasm use intel syntax?") .withRequiredArg().ofType(Boolean.class).describedAs("boolean").defaultsTo(false); OptionSpec<Boolean> optDrawIntraJumps = parser.accepts("drawIntraJumps", "Should perfasm draw jump arrows with the region?") .withRequiredArg().ofType(Boolean.class).describedAs("boolean").defaultsTo(true); OptionSpec<Boolean> optDrawInterJumps = parser.accepts("drawInterJumps", "Should perfasm draw jump arrows out of the region?") .withRequiredArg().ofType(Boolean.class).describedAs("boolean").defaultsTo(false); OptionSpec<String> optShowCounts = parser.accepts("showCounts", "How should perfasm show the event counts: " + ShowCounts.raw + " (unaltered), " + ShowCounts.norm + " (normalized to @Benchmark calls), " + ShowCounts.percent_total + " (percent of total events).") .withRequiredArg().ofType(String.class).describedAs("type").defaultsTo(ShowCounts.percent_total.toString()); addMyOptions(parser); set = ProfilerUtils.parseInitLine(initLine, parser); try { requestedEventNames = set.valuesOf(optEvents); regionRateThreshold = set.valueOf(optThresholdRate); regionShowTop = set.valueOf(optShowTop); regionTooBigThreshold = set.valueOf(optThreshold); printMargin = set.valueOf(optPrintMargin); mergeMargin = set.valueOf(optMergeMargin); mergeMethods = set.valueOf(optMergeMethods); delayMsec = set.valueOf(optDelay); lengthMsec = set.valueOf(optLength); skipAssembly = set.valueOf(optSkipAsm); skipInterpreter = set.valueOf(optSkipInterpreter); skipVMStubs = set.valueOf(optSkipVMStubs); savePerfOutput = set.valueOf(optPerfOut); savePerfOutputTo = set.valueOf(optPerfOutTo); savePerfOutputToFile = set.valueOf(optPerfOutToFile); savePerfBin = set.valueOf(optPerfBin); savePerfBinTo = set.valueOf(optPerfBinTo); savePerfBinFile = set.valueOf(optPerfBinToFile); saveLog = set.valueOf(optSaveLog); saveLogTo = set.valueOf(optSaveLogTo); saveLogToFile = set.valueOf(optSaveLogToFile); intelSyntax = set.valueOf(optIntelSyntax); drawIntraJumps = set.valueOf(optDrawInterJumps); drawInterJumps = set.valueOf(optDrawIntraJumps); showCounts = ShowCounts.valueOf(set.valueOf(optShowCounts)); } catch (OptionException | IllegalArgumentException e) { throw new ProfilerException(e.getMessage()); } } protected abstract void addMyOptions(OptionParser parser); @Override public Collection<String> addJVMOptions(BenchmarkParams params) { if (!skipAssembly) { Collection<String> opts = new ArrayList<>(); opts.addAll(Arrays.asList( "-XX:+UnlockDiagnosticVMOptions", "-XX:+LogCompilation", "-XX:LogFile=" + hsLog.getAbsolutePath(), "-XX:+PrintAssembly")); if (!skipInterpreter) { opts.add("-XX:+PrintInterpreter"); } if (!skipVMStubs) { opts.add("-XX:+PrintNMethods"); opts.add("-XX:+PrintNativeNMethods"); opts.add("-XX:+PrintSignatureHandlers"); opts.add("-XX:+PrintAdapterHandlers"); opts.add("-XX:+PrintStubCode"); } if (intelSyntax) { opts.add("-XX:PrintAssemblyOptions=intel"); } return opts; } else { return Collections.emptyList(); } } @Override public void beforeTrial(BenchmarkParams params) { // do nothing } @Override public Collection<? extends Result> afterTrial(BenchmarkResult br, long pid, File stdOut, File stdErr) { TextResult result = processAssembly(br); // we know these are not needed anymore, proactively delete hsLog.delete(); perfBinData.delete(); perfParsedData.delete(); return Collections.singleton(result); } @Override public boolean allowPrintOut() { return false; } @Override public boolean allowPrintErr() { return false; } /** * Parse profiler events from binary to text form. */ protected abstract void parseEvents(); /** * Read parsed events. * * @param skipMs Milliseconds to skip. * @param lenMs Milliseconds to capture after skip * @return Events. */ protected abstract PerfEvents readEvents(double skipMs, double lenMs); /** * Some profilers strip modifiers from event names. * To properly match the events in shared code, we need to know * what those events were stripped to. * @return stripped events */ protected List<String> stripEventNames(List<String> src) { return src; } /** * Get perf binary data extension (optional). * * @return Extension. */ protected abstract String perfBinaryExtension(); private TextResult processAssembly(BenchmarkResult br) { /** * 1. Parse binary events. */ parseEvents(); StringWriter sw = new StringWriter(); PrintWriter pw = new PrintWriter(sw); /** * 2. Read out PrintAssembly output */ Assembly assembly = readAssembly(hsLog.file()); if (assembly.size() > 0) { pw.printf("PrintAssembly processed: %d total address lines.%n", assembly.size()); } else if (skipAssembly) { pw.println(); pw.println("PrintAssembly skipped, Java methods are not resolved."); pw.println(); } else { pw.println(); pw.println("ERROR: No address lines detected in assembly capture. Make sure your JDK is properly configured to"); pw.println("print generated assembly. The most probable cause for this failure is that hsdis is not available,"); pw.println("or resides at the wrong path within the JDK. Try to run the same JDK with -XX:+PrintAssembly with"); pw.println("a simple non-JMH program and look for warning messages. For details, see the link below:"); pw.println(" https://wiki.openjdk.java.net/display/HotSpot/PrintAssembly"); pw.println(); } /** * 3. Read out perf output */ long skipMs; if (delayMsec == -1) { // not set skipMs = ProfilerUtils.measurementDelayMs(br); } else { skipMs = delayMsec; } double lenMs; if (lengthMsec == -1) { // not set lenMs = ProfilerUtils.measuredTimeMs(br); } else { lenMs = lengthMsec; } final PerfEvents events = readEvents(skipMs, lenMs); List<String> evNames = stripEventNames(requestedEventNames); if (!events.isEmpty()) { pw.printf("Perf output processed (skipped %.3f seconds):%n", skipMs / 1000D); int cnt = 1; for (int i = 0; i < evNames.size(); i++) { String stripped = evNames.get(i); String requested = requestedEventNames.get(i); pw.printf(" Column %d: %s%s (%d events)%n", cnt, stripped, (requested.equals(stripped) ? "" : " (" + requested + ")"), events.get(stripped).size()); cnt++; } pw.println(); } else { pw.println(); pw.println("ERROR: No perf data, make sure \"perf stat echo 1\" is indeed working;\n " + "or the collection delay is not running past the benchmark time."); pw.println(); } PrintContext context; { BenchmarkResultMetaData md = br.getMetadata(); long ops = Math.max(1, md.getMeasurementOps()); int majorScale; int minorScale; switch (showCounts) { case raw: majorScale = 1; minorScale = 0; for (long c : events.totalCounts.values()) { majorScale = Math.max(majorScale, (int)Math.ceil(Math.log10(c))); } break; case norm: majorScale = 2; minorScale = 1; for (long c : events.totalCounts.values()) { double d = Math.log10(1D * c / ops); if (d < 0) { minorScale = Math.max(minorScale, (int)Math.ceil(-d)); } else { majorScale = Math.max(majorScale, (int)Math.ceil(d)); } } break; case percent_total: majorScale = 3; minorScale = 2; break; default: throw new IllegalStateException("Unhandled enum: " + showCounts); } context = new PrintContext(showCounts, ops, majorScale + minorScale + 2, minorScale); } /** * 4. Figure out code regions */ final List<Region> regions = makeRegions(assembly, events, context); /** * 5. Figure out interesting regions, and print them out. * We would sort the regions by the hotness of the first (main) event type. */ final String mainEvent = evNames.get(0); regions.sort((o1, o2) -> Long.compare(o2.getEventCount(events, mainEvent), o1.getEventCount(events, mainEvent))); long threshold = (long) (regionRateThreshold * events.getTotalEvents(mainEvent)); boolean headerPrinted = false; int cnt = 1; for (Region r : regions) { if (r.getEventCount(events, mainEvent) > threshold) { if (!headerPrinted) { pw.printf("Hottest code regions (>%.2f%% \"%s\" events):%n", regionRateThreshold * 100, mainEvent); switch (showCounts) { case raw: pw.println(" Unaltered event counts are printed."); break; case norm: pw.println(" Event counts are normalized per @Benchmark call."); break; case percent_total: pw.println(" Event counts are percents of total event count."); break; default: throw new IllegalStateException("Unhandled enum: " + showCounts); } pw.println(); headerPrinted = true; } printDottedLine(pw, "Hottest Region " + cnt); pw.printf("%s, %s %n%n", r.desc().source(), r.desc().name()); r.printCode(pw, events); printDottedLine(pw); for (String event : evNames) { printLine(pw, events, event, r.getEventCount(events, event), context); } pw.println("<total for region " + cnt + ">"); pw.println(); cnt++; } } if (!headerPrinted) { pw.printf("WARNING: No hottest code region above the threshold (%.2f%%) for disassembly.%n", regionRateThreshold * 100); pw.println("Use \"hotThreshold\" profiler option to lower the filter threshold."); pw.println(); } int lenSource = 0; for (Region r : regions) { lenSource = Math.max(lenSource, r.desc().source().length()); } /** * 6. Print out the hottest regions */ { Multiset<String> total = new HashMultiset<>(); Multiset<String> other = new HashMultiset<>(); printDottedLine(pw, "Hottest Regions"); int shown = 0; for (Region r : regions) { if (shown++ < regionShowTop) { for (String event : evNames) { printLine(pw, events, event, r.getEventCount(events, event), context); } pw.printf("%" + lenSource + "s %s %n", r.desc().source(), r.desc().name()); } else { for (String event : evNames) { other.add(event, r.getEventCount(events, event)); } } for (String event : evNames) { total.add(event, r.getEventCount(events, event)); } } if (regions.size() - regionShowTop > 0) { for (String event : evNames) { printLine(pw, events, event, other.count(event), context); } pw.println("<...other " + (regions.size() - regionShowTop) + " warm regions...>"); } printDottedLine(pw); for (String event : evNames) { printLine(pw, events, event, total.count(event), context); } pw.println("<totals>"); pw.println(); } final Map<String, Multiset<String>> methodsByType = new HashMap<>(); final Map<String, Multiset<MethodDesc>> methods = new HashMap<>(); for (String event : evNames) { methodsByType.put(event, new HashMultiset<>()); methods.put(event, new HashMultiset<>()); } for (Region r : regions) { for (String event : evNames) { long count = r.getEventCount(events, event); methods.get(event).add(r.desc(), count); methodsByType.get(event).add(r.desc().source(), count); } } /** * Print out hottest methods */ { printDottedLine(pw, "Hottest Methods (after inlining)"); Multiset<String> total = new HashMultiset<>(); Multiset<String> other = new HashMultiset<>(); int shownMethods = 0; List<MethodDesc> top = Multisets.sortedDesc(methods.get(mainEvent)); for (MethodDesc m : top) { if (shownMethods++ < regionShowTop) { for (String event : evNames) { printLine(pw, events, event, methods.get(event).count(m), context); } pw.printf("%" + lenSource + "s %s %n", m.source(), m.name()); } else { for (String event : evNames) { other.add(event, methods.get(event).count(m)); } } for (String event : evNames) { total.add(event, methods.get(event).count(m)); } } if (top.size() - regionShowTop > 0) { for (String event : evNames) { printLine(pw, events, event, other.count(event), context); } pw.println("<...other " + (top.size() - regionShowTop) + " warm methods...>"); } printDottedLine(pw); for (String event : evNames) { printLine(pw, events, event, total.count(event), context); } pw.println("<totals>"); pw.println(); } /** * Print hot methods distribution */ { printDottedLine(pw, "Distribution by Source"); for (String m : Multisets.sortedDesc(methodsByType.get(mainEvent))) { for (String event : evNames) { printLine(pw, events, event, methodsByType.get(event).count(m), context); } pw.printf("%" + lenSource + "s%n", m); } printDottedLine(pw); for (String event : evNames) { printLine(pw, events, event, methodsByType.get(event).size(), context); } pw.println("<totals>"); pw.println(); } /** * Final checks on assembly: */ { Set<Long> addrHistory = new HashSet<>(); for (Long addr : assembly.addressMap.keySet()) { if (!addrHistory.add(addr)) { pw.println("WARNING: Duplicate instruction addresses detected. This is probably due to compiler reusing\n " + "the code arena for the new generated code. We can not differentiate between methods sharing\n" + "the same addresses, and therefore the profile might be wrong. Increasing generated code\n" + "storage might help."); } } } { int sum = 0; for (Long v : events.totalCounts.values()) { sum += v; } if (sum < 1000) { pw.println("WARNING: The perf event count is suspiciously low (" + sum + "). The performance data might be"); pw.println("inaccurate or misleading. Try to do the profiling again, or tune up the sampling frequency."); pw.println("With some profilers on Mac OS X, System Integrity Protection (SIP) may prevent profiling."); pw.println("In such case, temporarily disabling SIP with 'csrutil disable' might help."); } } /** * Print perf output, if needed: */ if (savePerfOutput) { String target = (savePerfOutputToFile == null) ? savePerfOutputTo + "/" + br.getParams().id() + ".perf" : savePerfOutputToFile; try { FileUtils.copy(perfParsedData.getAbsolutePath(), target); pw.println("Perf output saved to " + target); } catch (IOException e) { pw.println("Unable to save perf output to " + target); } } /** * Print binary perf output, if needed: */ if (savePerfBin) { String target = (savePerfBinFile == null) ? savePerfBinTo + "/" + br.getParams().id() + perfBinaryExtension() : savePerfBinFile; try { FileUtils.copy(perfBinData.getAbsolutePath(), target); pw.println("Perf binary output saved to " + target); } catch (IOException e) { pw.println("Unable to save perf binary output to " + target); } } /** * Print annotated assembly, if needed: */ if (saveLog) { String target = (saveLogToFile == null) ? saveLogTo + "/" + br.getParams().id() + ".log" : saveLogToFile; try (FileOutputStream asm = new FileOutputStream(target); PrintWriter pwAsm = new PrintWriter(asm)) { for (ASMLine line : assembly.lines) { for (String event : evNames) { long count = (line.addr != null) ? events.get(event).count(line.addr) : 0; printLine(pwAsm, events, event, count, context); } pwAsm.println(line.code); } pw.println("Perf-annotated Hotspot log is saved to " + target); } catch (IOException e) { pw.println("Unable to save Hotspot log to " + target); } } pw.flush(); pw.close(); return new TextResult(sw.toString(), "asm"); } private static void printLine(PrintWriter pw, PerfEvents events, String event, long count, PrintContext context) { if (count > 0) { switch (context.mode) { case raw: pw.printf("%" + context.formatWidth + "d ", count); break; case norm: pw.printf("%" + context.formatWidth + "." + context.formatMinor + "f ", 100.0 * count / context.ops); break; case percent_total: pw.printf("%" + context.formatWidth + "." + context.formatMinor + "f%% ", 100.0 * count / events.getTotalEvents(event)); break; default: throw new IllegalStateException("Unhandled enum: " + context.mode); } } else { pw.printf("%" + context.formatWidth + "s ", ""); } } private void printDottedLine(PrintWriter pw) { printDottedLine(pw, null); } private void printDottedLine(PrintWriter pw, String header) { final int HEADER_WIDTH = 100; pw.print("...."); if (header != null) { header = "[" + header + "]"; pw.print(header); } else { header = ""; } for (int c = 0; c < HEADER_WIDTH - 4 - header.length(); c++) { pw.print("."); } pw.println(); } private List<Region> makeRegions(Assembly asms, PerfEvents events, PrintContext context) { List<String> strippedEvents = stripEventNames(requestedEventNames); List<Region> regions = new ArrayList<>(); SortedSet<Long> allAddrs = events.getAllAddresses(); for (Interval intv : figureHotIntervals(allAddrs, asms)) { SortedSet<Long> eventfulAddrs = allAddrs.subSet(intv.src, intv.dst + 1); List<ASMLine> regionLines = asms.getLines(intv.src, intv.dst, printMargin); if (!regionLines.isEmpty()) { // has some associated assembly // TODO: Should scan and split regions for multiple descs? MethodDesc desc = asms.getMethod(intv.src); if (desc == null) { desc = MethodDesc.unknown(); } regions.add(new GeneratedRegion(strippedEvents, asms, desc, intv.src, intv.dst, regionLines, eventfulAddrs, regionTooBigThreshold, drawIntraJumps, drawInterJumps, context)); } else { // has no assembly, should be a native region // TODO: Should scan and split regions for multiple descs? MethodDesc desc = events.getMethod(intv.src); if (desc == null) { desc = MethodDesc.unknown(); } regions.add(new NativeRegion(desc, intv.src, intv.dst, eventfulAddrs)); } } return regions; } private List<Interval> figureHotIntervals(SortedSet<Long> addrs, Assembly asms) { if (addrs.isEmpty()) { return Collections.emptyList(); } List<Interval> intervals = new ArrayList<>(); long begAddr = addrs.first(); long lastAddr = addrs.first(); for (long addr : addrs) { if (addr - lastAddr > mergeMargin) { addInterval(intervals, begAddr, lastAddr, asms); begAddr = addr; } lastAddr = addr; } if (begAddr != lastAddr) { addInterval(intervals, begAddr, lastAddr, asms); } return intervals; } private void addInterval(List<Interval> intervals, long begAddr, long lastAddr, Assembly asms) { if (!mergeMethods || intervals.isEmpty()) { intervals.add(new Interval(begAddr, lastAddr)); } else { Interval prev = intervals.get(intervals.size() - 1); MethodDesc prevMethod = asms.getMethod(prev.src); MethodDesc method = asms.getMethod(begAddr); if (prevMethod == null || !prevMethod.equals(method)) { intervals.add(new Interval(begAddr, lastAddr)); } else { intervals.set(intervals.size() - 1, new Interval(prev.src, lastAddr)); } } } private Collection<Collection<String>> splitAssembly(File stdOut) { try (FileReader in = new FileReader(stdOut); BufferedReader br = new BufferedReader(in)) { Multimap<Long, String> writerToLines = new HashMultimap<>(); long writerId = -1L; final Pattern writerThreadPattern = Pattern.compile("(.*)<writer thread='(.*)'>(.*)"); String line; while ((line = br.readLine()) != null) { // Parse the writer threads IDs: // <writer thread='140703710570240'/> if (line.contains("<writer thread=")) { Matcher m = writerThreadPattern.matcher(line); if (m.matches()) { try { writerId = Long.parseLong(m.group(2)); } catch (NumberFormatException e) { // something is wrong, try to recover } } continue; } writerToLines.put(writerId, line); } Collection<Collection<String>> r = new ArrayList<>(); for (long id : writerToLines.keys()) { r.add(writerToLines.get(id)); } return r; } catch (IOException e) { return Collections.emptyList(); } } private Assembly readAssembly(File stdOut) { List<ASMLine> lines = new ArrayList<>(); SortedMap<Long, Integer> addressMap = new TreeMap<>(); IntervalMap<MethodDesc> stubs = new IntervalMap<>(); IntervalMap<MethodDesc> javaMethods = new IntervalMap<>(); Set<Interval> intervals = new HashSet<>(); CountingMap<String> methodVersions = new CountingMap<>(); // Parsing the interpreter/runtime stub: // ---------------------------------------------------------------------- // invokehandle 233 invokehandle [0x00007f631d023100, 0x00007f631d0233c0] 704 bytes // StubRoutines::catch_exception [0x00007feb43fa7b27, 0x00007feb43fa7b46[ (31 bytes) // JDK 13 adds another "-------" line after StubRoutines line, so we need to filter out // mismatched lines that follow it. This is why regexp is anchored at the start of the line. // Example: // // StubRoutines::updateBytesCRC32 [0x0000ffff6c819700, 0x0000ffff6c819870] (368 bytes) // -------------------------------------------------------------------------------- // 0x0000ffff6c819700: stp x29, x30, [sp, #-16]! <--- do not match this // 0x0000ffff6c819704: mov x29, sp // 0x0000ffff6c819708: mvn w0, w0 final Pattern interpreterStubPattern = Pattern.compile("^(\\S.*)( +)\\[(.+), (.+)[\\]\\[](.*)"); // <nmethod compile_id='481' compiler='C1' level='3' entry='0x00007f26f51fb640' size='1392' // address='0x00007f26f51fb4d0' relocation_offset='296' insts_offset='368' stub_offset='976' // scopes_data_offset='1152' scopes_pcs_offset='1208' dependencies_offset='1368' nul_chk_table_offset='1376' // method='java/lang/reflect/Constructor getParameterTypes ()[Ljava/lang/Class;' bytes='11' // count='258' iicount='258' stamp='8.590'/> final Pattern nmethodPattern = Pattern.compile("(.*?)<nmethod (.*?)/>(.*?)"); for (Collection<String> cs : splitAssembly(stdOut)) { String prevLine = ""; for (String line : cs) { String trim = line.trim(); if (trim.isEmpty()) { // Filter out empty lines for denser output, more efficient matching, // and trustworthy prevLine. continue; } List<Long> addrs = parseAddresses(trim, true, true); ASMLine asmLine = new ASMLine(line); // Handle the most frequent case first. if (addrs.size() > 0) { long startAddr = addrs.get(0); int idx = lines.size(); addressMap.put(startAddr, idx); asmLine = new ASMLine(startAddr, line); if (addrs.size() > 1 && (drawInterJumps || drawIntraJumps)) { for (int c = 1; c < addrs.size(); c++) { long targetAddr = addrs.get(c); intervals.add(new Interval(startAddr, targetAddr)); } } } if (prevLine.contains("--------") || line.contains("StubRoutines::")) { Matcher matcher = interpreterStubPattern.matcher(line); if (matcher.matches()) { String name = matcher.group(1); List<Long> stubAddrs = parseAddresses(trim, true, false); if (stubAddrs.size() == 2) { long startAddr = stubAddrs.get(0); long endAddr = stubAddrs.get(1); if (line.contains("StubRoutines::")) { stubs.add(MethodDesc.runtimeStub(name), startAddr, endAddr); } else { stubs.add(MethodDesc.interpreter(name), startAddr, endAddr); } } } } if (line.contains("<nmethod")) { Matcher matcher = nmethodPattern.matcher(line); if (matcher.matches()) { String body = matcher.group(2); body = body.replaceAll("='", "="); String[] kvs = body.split("' "); HashMap<String, String> map = new HashMap<>(); for (String kv : kvs) { String[] pair = kv.split("="); // Guard against "key=''" if (pair.length == 2) { map.put(pair[0], pair[1]); } else { map.put(pair[0], null); } } // Record the starting address for the method List<Long> entryAddrs = parseAddresses(map.get("entry"), true, true); long addr = entryAddrs.get(0); MethodDesc desc = MethodDesc.javaMethod( map.get("method"), map.get("compiler"), map.get("level"), methodVersions.incrementAndGet(map.get("method")), map.get("compile_id")); javaMethods.add( desc, addr, addr + Long.parseLong(map.get("size")) ); } } lines.add(asmLine); prevLine = line; } } // Important to get the order right: all Java methods take precedence over interpreter/runtime stubs. IntervalMap<MethodDesc> methodMap = new IntervalMap<>(); methodMap.merge(stubs); methodMap.merge(javaMethods); return new Assembly(lines, addressMap, methodMap, intervals); } private static final List<Long> EMPTY_LIST_LONGS = Collections.unmodifiableList(new ArrayList<>()); private static final Pattern ADDR_LINE_SPLIT = Pattern.compile("\\W+"); static List<Long> parseAddresses(String line, boolean alreadyTrimmed, boolean shouldStartWithAddr) { if (!alreadyTrimmed) { line = line.trim(); } List<Long> addrs = new ArrayList<>(); String[] elements = ADDR_LINE_SPLIT.split(line); for (int i = 0; i < elements.length; i++) { String el = elements[i]; String str = null; if (el.startsWith("0x")) { // AT&T address format str = el.replace("0x", "").replace(":", ""); } else if (el.endsWith("h")) { // Intel address format str = el.replace("h", ""); } else if (shouldStartWithAddr && (i == 0)) { // First element is not address, the line is wrong return EMPTY_LIST_LONGS; } if (str != null) { try { addrs.add(Long.parseLong(str, 16)); } catch (NumberFormatException nfe) { // It looked like an address, but was not. } } } return Collections.unmodifiableList(addrs); } protected static class PerfEvents { final Map<String, Multiset<Long>> events; final IntervalMap<MethodDesc> methods; final Map<String, Long> totalCounts; PerfEvents(Collection<String> tracedEvents, Map<String, Multiset<Long>> events, IntervalMap<MethodDesc> methods) { this.events = events; this.methods = methods; this.totalCounts = new HashMap<>(); for (String event : tracedEvents) { totalCounts.put(event, events.get(event).size()); } } public boolean isEmpty() { return events.isEmpty(); } public Multiset<Long> get(String event) { return events.get(event); } public SortedSet<Long> getAllAddresses() { SortedSet<Long> addrs = new TreeSet<>(); for (Multiset<Long> e : events.values()) { addrs.addAll(e.keys()); } return addrs; } public Long getTotalEvents(String event) { return totalCounts.get(event); } public MethodDesc getMethod(long addr) { return methods.get(addr); } } static class Assembly { final List<ASMLine> lines; final SortedMap<Long, Integer> addressMap; final IntervalMap<MethodDesc> methodMap; final Set<Interval> intervals; public Assembly(List<ASMLine> lines, SortedMap<Long, Integer> addressMap, IntervalMap<MethodDesc> methodMap, Set<Interval> intervals) { this.lines = lines; this.addressMap = addressMap; this.methodMap = methodMap; this.intervals = intervals; } public int size() { // We only care about the address lines. return addressMap.size(); } private boolean isSameMethod(MethodDesc method, int idx) { ASMLine line = lines.get(idx); Long addr = line != null ? line.addr : null; MethodDesc m = addr != null ? getMethod(addr) : null; // If we cannot find a method for the line, assume it "equals" return (m == null) || Objects.equals(m, method); } private int adjustWindowForward(MethodDesc method, int beginIdx, int window) { for (; beginIdx > 0 && window > 0; beginIdx--, window--) { if (!isSameMethod(method, beginIdx - 1)) { return beginIdx; } } return beginIdx; } private int adjustWindowBackward(MethodDesc method, int endIdx, int window) { int size = lines.size(); for (; endIdx < size && window > 0; endIdx++, window--) { if (!isSameMethod(method, endIdx)) { return endIdx; } } return endIdx; } public List<ASMLine> getLines(long begin, long end, int window) { SortedMap<Long, Integer> tailMap = addressMap.tailMap(begin); Long beginAddr; Integer beginIdx; if (!tailMap.isEmpty()) { beginAddr = tailMap.firstKey(); beginIdx = addressMap.get(beginAddr); } else { return Collections.emptyList(); } SortedMap<Long, Integer> headMap = addressMap.headMap(end); Long endAddr; Integer endIdx; if (!headMap.isEmpty()) { endAddr = headMap.lastKey(); endIdx = addressMap.get(endAddr); } else { return Collections.emptyList(); } MethodDesc method = getMethod(begin); beginIdx = adjustWindowForward(method, beginIdx, window); endIdx = adjustWindowBackward(method, endIdx, 2 + window); // Compensate for minute discrepancies if (beginIdx < endIdx) { return lines.subList(beginIdx, endIdx); } else { return Collections.emptyList(); } } public MethodDesc getMethod(long addr) { return methodMap.get(addr); } } static class ASMLine { final Long addr; final String code; ASMLine(String code) { this(null, code); } ASMLine(Long addr, String code) { this.addr = addr; this.code = code; } } static class Region { final MethodDesc method; final long begin; final long end; final Set<Long> eventfulAddrs; final Map<String, Long> eventCountCache; Region(MethodDesc method, long begin, long end, Set<Long> eventfulAddrs) { this.method = method; this.begin = begin; this.end = end; this.eventfulAddrs = eventfulAddrs; this.eventCountCache = new HashMap<>(); } long getEventCount(PerfEvents events, String event) { if (!eventCountCache.containsKey(event)) { Multiset<Long> evs = events.get(event); long count = 0; for (Long addr : eventfulAddrs) { count += evs.count(addr); } eventCountCache.put(event, count); } return eventCountCache.get(event); } public void printCode(PrintWriter pw, PerfEvents events) { pw.println("<no code>"); } public MethodDesc desc() { return method; } } static class GeneratedRegion extends Region { final Collection<String> tracedEvents; final Assembly asms; final Collection<ASMLine> code; final int threshold; final boolean drawIntraJumps; final boolean drawInterJumps; final PrintContext context; GeneratedRegion(Collection<String> tracedEvents, Assembly asms, MethodDesc desc, long begin, long end, Collection<ASMLine> code, Set<Long> eventfulAddrs, int threshold, boolean drawIntraJumps, boolean drawInterJumps, PrintContext context) { super(desc, begin, end, eventfulAddrs); this.tracedEvents = tracedEvents; this.asms = asms; this.code = code; this.threshold = threshold; this.drawIntraJumps = drawIntraJumps; this.drawInterJumps = drawInterJumps; this.context = context; } @Override public void printCode(PrintWriter pw, PerfEvents events) { if (code.size() > threshold) { pw.printf(" <region is too big to display, has %d lines, but threshold is %d>%n", code.size(), threshold); } else { long beginLine = begin; long endLine = end; for (ASMLine line : code) { Long addr = line.addr; if (addr != null) { beginLine = Math.min(beginLine, addr); endLine = Math.max(endLine, addr); } } Set<Interval> interIvs = new TreeSet<>(); Set<Interval> intraIvs = new TreeSet<>(); for (Interval it : asms.intervals) { boolean srcInline = (beginLine < it.src && it.src < endLine); boolean dstInline = (beginLine < it.dst && it.dst < endLine); if (srcInline && dstInline) { if (drawInterJumps) { interIvs.add(it); } } else if (srcInline || dstInline) { if (drawIntraJumps) { intraIvs.add(it); } } } long prevAddr = 0; for (ASMLine line : code) { for (String event : tracedEvents) { long count = (line.addr != null) ? events.get(event).count(line.addr) : 0; printLine(pw, events, event, count, context); } long addr; long evAddr; if (line.addr == null) { addr = prevAddr; evAddr = -1; } else { addr = line.addr; evAddr = addr; prevAddr = addr; } for (Interval it : intraIvs) { printInterval(pw, it, addr, evAddr, false); } for (Interval it : interIvs) { printInterval(pw, it, addr, evAddr, true); } pw.println(line.code); } } } private void printInterval(PrintWriter pw, Interval it, long addr, long evAddr, boolean inline) { if (it.src < it.dst) { // flows downwards if (it.src == evAddr) { pw.print("\u256d"); } else if (it.dst == evAddr) { pw.print("\u2198"); } else if ((it.src <= addr) && (addr < it.dst)) { if (inline) { pw.print("\u2502"); } else { pw.print("\u2575"); } } else { pw.print(" "); } } else { // flows upwards if (it.src == evAddr) { pw.print("\u2570"); } else if (it.dst == evAddr) { pw.print("\u2197"); } else if ((it.dst <= addr) && (addr < it.src)) { if (inline) { pw.print("\u2502"); } else { pw.print("\u2575"); } } else { pw.print(" "); } } } } static class NativeRegion extends Region { NativeRegion(MethodDesc desc, long begin, long end, Set<Long> eventfulAddrs) { super(desc, begin, end, eventfulAddrs); } @Override public void printCode(PrintWriter pw, PerfEvents events) { pw.println(" <no assembly is recorded, native region>"); } } static class UnknownRegion extends Region { UnknownRegion() { super(MethodDesc.unknown(), 0L, 0L, Collections.singleton(0L)); } @Override public void printCode(PrintWriter pw, PerfEvents events) { pw.println(" <no assembly is recorded, unknown region>"); } } static class MethodDesc { private final String name; private final String source; protected MethodDesc(String name, String source) { this.name = name; this.source = source; } public static MethodDesc unresolved() { return new MethodDesc("<unresolved>", ""); } public static MethodDesc unknown() { return new MethodDesc("<unknown>", ""); } public static MethodDesc kernel() { return new MethodDesc("<kernel>", "kernel"); } public static MethodDesc interpreter(String name) { return new MethodDesc(name, "interpreter"); } public static MethodDesc runtimeStub(String name) { return new MethodDesc(name, "runtime stub"); } public static MethodDesc javaMethod(String name, String compiler, String level, int ver, String compileId) { String methodName = name.replace("/", ".").replaceFirst(" ", "::").split(" ")[0]; return new MethodDesc( methodName + ", version " + ver + ", compile id " + compileId, (compiler != null ? compiler : "Unknown") + (level != null ? ", level " + level : "") ); } public static MethodDesc nativeMethod(String symbol, String lib) { return new MethodDesc(symbol, lib); } public String name() { return name; } public String source() { return source; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; MethodDesc that = (MethodDesc) o; if (!name.equals(that.name)) return false; return source.equals(that.source); } @Override public int hashCode() { int result = name.hashCode(); result = 31 * result + source.hashCode(); return result; } @Override public String toString() { return "MethodDesc{" + "name='" + name + '\'' + ", source='" + source + '\'' + '}'; } } private static class PrintContext { private final ShowCounts mode; private final long ops; private final int formatWidth; private final int formatMinor; public PrintContext(ShowCounts mode, long ops, int formatWidth, int formatMinor) { this.mode = mode; this.ops = ops; this.formatWidth = formatWidth; this.formatMinor = formatMinor; } } }
56,466
37.702536
143
java
jmh
jmh-master/jmh-core/src/main/java/org/openjdk/jmh/profile/AsyncProfiler.java
/* * Copyright (c) 2020, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package org.openjdk.jmh.profile; import joptsimple.OptionException; import joptsimple.OptionParser; import joptsimple.OptionSet; import joptsimple.OptionSpec; import org.openjdk.jmh.infra.BenchmarkParams; import org.openjdk.jmh.infra.IterationParams; import org.openjdk.jmh.results.BenchmarkResult; import org.openjdk.jmh.results.IterationResult; import org.openjdk.jmh.results.Result; import org.openjdk.jmh.results.TextResult; import org.openjdk.jmh.runner.IterationType; import org.openjdk.jmh.util.FileUtils; import java.io.File; import java.io.IOException; import java.io.PrintWriter; import java.io.StringWriter; import java.util.*; /** * A profiler based on <a href="https://github.com/jvm-profiling-tools/async-profiler/">async-profiler</a>. * * @author Jason Zaugg */ public final class AsyncProfiler implements ExternalProfiler, InternalProfiler { private final JavaApi instance; private final boolean verbose; private final Direction direction; private final String profilerConfig; private final List<OutputType> output; private final String outputFilePrefix; private final File outDir; private File trialOutDir; private final int traces; private final int flat; private boolean isVersion1x; private boolean warmupStarted; private boolean measurementStarted; private int measurementIterationCount; private final LinkedHashSet<File> generated = new LinkedHashSet<>(); public AsyncProfiler(String initLine) throws ProfilerException { OptionParser parser = new OptionParser(); parser.formatHelpWith(new ProfilerOptionFormatter("async")); OptionSpec<OutputType> optOutput = parser.accepts("output", "Output format(s). Supported: " + EnumSet.allOf(OutputType.class) + ".") .withRequiredArg().ofType(OutputType.class).withValuesSeparatedBy(",").describedAs("format+").defaultsTo(OutputType.text); OptionSpec<Direction> optDirection = parser.accepts("direction", "Direction(s) of flame graph. Supported: " + EnumSet.allOf(Direction.class) + ".") .withRequiredArg().ofType(Direction.class).describedAs("direction").defaultsTo(Direction.both); OptionSpec<String> optLibPath = parser.accepts("libPath", "Location of asyncProfiler library. If not specified, System.loadLibrary will be used " + "and the library must be made available to the forked JVM in an entry of -Djava.library.path, " + "LD_LIBRARY_PATH (Linux), or DYLD_LIBRARY_PATH (Mac OS).") .withRequiredArg().ofType(String.class).describedAs("path"); OptionSpec<String> optEvent = parser.accepts("event", "Event to sample: cpu, alloc, lock, wall, itimer; com.foo.Bar.methodName; any event from `perf list` e.g. cache-misses") .withRequiredArg().ofType(String.class).describedAs("event").defaultsTo("cpu"); String secondaryEventOk = "May be captured as a secondary event under output=jfr."; OptionSpec<String> optAlloc = parser.accepts("alloc", "Enable allocation profiling. Optional argument (e.g. =512k) reduces sampling from the default of one-sample-per-TLAB. " + secondaryEventOk) .withOptionalArg().ofType(String.class).describedAs("sample bytes"); OptionSpec<String> optLock = parser.accepts("lock", "Enable lock profiling. Optional argument (e.g. =1ms) limits capture based on lock duration. " + secondaryEventOk) .withOptionalArg().ofType(String.class).describedAs("duration"); OptionSpec<String> optDir = parser.accepts("dir", "Output directory.") .withRequiredArg().ofType(String.class).describedAs("dir"); OptionSpec<Long> optInterval = parser.accepts("interval", "Profiling interval.") .withRequiredArg().ofType(Long.class).describedAs("ns"); OptionSpec<Integer> optJstackDepth = parser.accepts("jstackdepth", "Maximum Java stack depth.") .withRequiredArg().ofType(Integer.class).describedAs("frames"); OptionSpec<Long> optFrameBuf = parser.accepts("framebuf", "Size of profiler framebuffer.") .withRequiredArg().ofType(Long.class).describedAs("bytes"); OptionSpec<Boolean> optFilter = parser.accepts("filter", "Enable thread filtering during collection. Useful for wall clock profiling, " + "but only if the workload registers the relevant threads programatically " + "via `AsyncProfiler.JavaApi.getInstance().filterThread(thread, enabled)`.") .withRequiredArg().ofType(Boolean.class).defaultsTo(false).describedAs("boolean"); OptionSpec<Boolean> optThreads = parser.accepts("threads", "Profile threads separately.") .withRequiredArg().ofType(Boolean.class).describedAs("bool"); OptionSpec<Boolean> optSimple = parser.accepts("simple", "Simple class names instead of FQN.") .withRequiredArg().ofType(Boolean.class).describedAs("bool"); OptionSpec<Boolean> optSig = parser.accepts("sig", "Print method signatures.") .withRequiredArg().ofType(Boolean.class).describedAs("bool"); OptionSpec<Boolean> optAnn = parser.accepts("ann", "Annotate Java method names.") .withRequiredArg().ofType(Boolean.class).describedAs("bool"); OptionSpec<String> optInclude = parser.accepts("include", "Output only stack traces containing the specified pattern.") .withRequiredArg().withValuesSeparatedBy(",").ofType(String.class).describedAs("regexp+"); OptionSpec<String> optExclude = parser.accepts("exclude", "Exclude stack traces with the specified pattern.") .withRequiredArg().withValuesSeparatedBy(",").ofType(String.class).describedAs("regexp+"); OptionSpec<String> optRawCommand = parser.accepts("rawCommand", "Command to pass directly to async-profiler. Use to access new features of JMH " + "profiler that are not yet supported in this option parser.") .withRequiredArg().ofType(String.class).describedAs("command"); OptionSpec<String> optTitle = parser.accepts("title", "SVG title.") .withRequiredArg().ofType(String.class).describedAs("string"); OptionSpec<Long> optWidth = parser.accepts("width", "SVG width.") .withRequiredArg().ofType(Long.class).describedAs("pixels"); OptionSpec<Long> optMinWidth = parser.accepts("minwidth", "Skip frames smaller than px") .withRequiredArg().ofType(Long.class).describedAs("pixels"); OptionSpec<Boolean> optAllKernel = parser.accepts("allkernel", "Only include kernel-mode events.") .withRequiredArg().ofType(Boolean.class).describedAs("bool"); OptionSpec<Boolean> optAllUser = parser.accepts("alluser", "Only include user-mode events.") .withRequiredArg().ofType(Boolean.class).describedAs("bool"); OptionSpec<CStackMode> optCStack = parser.accepts("cstack", "How to traverse C stack: Supported: " + EnumSet.allOf(CStackMode.class) + ".") .withRequiredArg().ofType(CStackMode.class).describedAs("mode"); OptionSpec<Boolean> optVerbose = parser.accepts("verbose", "Output the sequence of commands.") .withRequiredArg().ofType(Boolean.class).defaultsTo(false).describedAs("bool"); OptionSpec<Integer> optTraces = parser.accepts("traces", "Number of top traces to include in the default output.") .withRequiredArg().ofType(Integer.class).defaultsTo(200).describedAs("int"); OptionSpec<Integer> optFlat = parser.accepts("flat", "Number of top flat profiles to include in the default output.") .withRequiredArg().ofType(Integer.class).defaultsTo(200).describedAs("int"); OptionSet set = ProfilerUtils.parseInitLine(initLine, parser); try { ProfilerOptionsBuilder builder = new ProfilerOptionsBuilder(set); if (!set.has(optDir)) { outDir = new File(System.getProperty("user.dir")); } else { outDir = new File(set.valueOf(optDir)); } builder.appendIfExists(optInterval); builder.appendIfExists(optJstackDepth); builder.appendIfTrue(optThreads); builder.appendIfTrue(optSimple); builder.appendIfTrue(optSig); builder.appendIfTrue(optAnn); builder.appendIfExists(optFrameBuf); if (optFilter.value(set)) { builder.appendRaw("filter"); } builder.appendMulti(optInclude); builder.appendMulti(optExclude); builder.appendIfExists(optTitle); builder.appendIfExists(optWidth); builder.appendIfExists(optMinWidth); builder.appendIfTrue(optAllKernel); builder.appendIfTrue(optAllUser); builder.appendIfExists(optCStack); if (set.has(optRawCommand)) { builder.appendRaw(optRawCommand.value(set)); } traces = optTraces.value(set); flat = optFlat.value(set); try { if (set.has(optLibPath)) { instance = JavaApi.getInstance(optLibPath.value(set)); } else { instance = JavaApi.getInstance(); } } catch (UnsatisfiedLinkError e) { throw new ProfilerException("Unable to load async-profiler. Ensure asyncProfiler library " + "is on LD_LIBRARY_PATH (Linux), DYLD_LIBRARY_PATH (Mac OS), or -Djava.library.path. " + "Alternatively, point to explicit library location with -prof async:libPath=<path>.", e); } verbose = optVerbose.value(set); try { String version = instance.execute("version"); if (verbose) { System.out.println("[async-profiler] version=" + version); } isVersion1x = version.startsWith("1."); } catch (IOException e) { throw new ProfilerException(e); } direction = optDirection.value(set); output = optOutput.values(set); // Secondary events are those that may be collected simultaneously with a primary event in a JFR profile. // To be used as such, we require they are specifed with the lock and alloc option, rather than event=lock, // event=alloc. Set<String> secondaryEvents = new HashSet<>(); if (set.has(optAlloc)) { secondaryEvents.add("alloc"); builder.append(optAlloc); } if (set.has(optLock)) { secondaryEvents.add("lock"); builder.append(optLock); } if (set.has(optEvent)) { String evName = set.valueOf(optEvent); if (evName.contains(",")) { throw new ProfilerException("Event name should not contain commas: " + evName); } outputFilePrefix = evName; builder.append(optEvent); } else { if (secondaryEvents.isEmpty()) { // Default to the cpu event if no events at all are selected. builder.appendRaw("event=cpu"); outputFilePrefix = "cpu"; } else if (secondaryEvents.size() == 1) { // No primary event, one secondary -- promote it to the primary event. This means any output // format is allowed and the event name will be included in the output file name. outputFilePrefix = secondaryEvents.iterator().next(); secondaryEvents.clear(); } else { outputFilePrefix = "profile"; } } if (!secondaryEvents.isEmpty()) { if (isVersion1x) { throw new ProfilerException("Secondary event capture not supported on async-profiler 1.x"); } if (output.size() > 1 || output.get(0) != OutputType.jfr) { throw new ProfilerException("Secondary event capture is only supported with output=" + OutputType.jfr.name()); } } profilerConfig = builder.profilerOptions(); } catch (OptionException e) { throw new ProfilerException(e.getMessage()); } } @Override public void beforeIteration(BenchmarkParams benchmarkParams, IterationParams iterationParams) { if (trialOutDir == null) { createTrialOutDir(benchmarkParams); } if (iterationParams.getType() == IterationType.WARMUP) { if (!warmupStarted) { // Collect profiles during warmup to warmup the profiler itself. start(); warmupStarted = true; } } if (iterationParams.getType() == IterationType.MEASUREMENT) { if (!measurementStarted) { if (warmupStarted) { // Discard samples collected during warmup... execute("stop"); } // ...and start collecting again. start(); measurementStarted = true; } } } private void start() { if (output.contains(OutputType.jfr)) { execute("start," + profilerConfig + ",file=" + outputFile("jfr-%s.jfr").getAbsolutePath()); } else { execute("start," + profilerConfig); } } @Override public Collection<? extends Result> afterIteration(BenchmarkParams benchmarkParams, IterationParams iterationParams, IterationResult iterationResult) { if (iterationParams.getType() == IterationType.MEASUREMENT) { measurementIterationCount += 1; if (measurementIterationCount == iterationParams.getCount()) { return Collections.singletonList(stopAndDump()); } } return Collections.emptyList(); } private void createTrialOutDir(BenchmarkParams benchmarkParams) { if (trialOutDir == null) { // async-profiler expands %p to PID and %t to timestamp, make sure we don't // include % in the file name. String fileName = benchmarkParams.id().replace("%", "_"); trialOutDir = new File(outDir, fileName); trialOutDir.mkdirs(); } } private TextResult stopAndDump() { execute("stop"); StringWriter sw = new StringWriter(); PrintWriter pw = new PrintWriter(sw); for (OutputType outputType : output) { switch (outputType) { case text: File out = outputFile("summary-%s.txt"); if (isVersion1x) { dump(out, "summary,flat=" + flat + ",traces=" + traces); } else { dump(out, "flat=" + flat + ",traces=" + traces); } try { for (String line : FileUtils.readAllLines(out)) { pw.println(line); } } catch (IOException e) { throw new RuntimeException(e); } break; case collapsed: dump(outputFile("collapsed-%s.csv"), "collapsed"); break; case flamegraph: // The last SVG-enabled version is 1.x String ext = isVersion1x ? "svg" : "html"; if (direction == Direction.both || direction == Direction.forward) { dump(outputFile("flame-%s-forward." + ext), "flamegraph"); } if (direction == Direction.both || direction == Direction.reverse) { dump(outputFile("flame-%s-reverse." + ext), "flamegraph,reverse"); } break; case tree: dump(outputFile("tree-%s.html"), "tree"); break; case jfr: // JFR is already dumped into file by async-profiler. break; } } pw.println("Async profiler results:"); for (File file : generated) { pw.print(" "); pw.println(file.getPath()); } pw.flush(); pw.close(); return new TextResult(sw.toString(), "async"); } private void dump(File target, String command) { execute(command + "," + profilerConfig + ",file=" + target.getAbsolutePath()); } private File outputFile(String fileNameFormat) { File output = new File(trialOutDir, String.format(fileNameFormat, outputFilePrefix)); generated.add(output); return output; } private String execute(String command) { if (verbose) { System.out.println("[async-profiler] " + command); } try { return instance.execute(command); } catch (IOException e) { throw new RuntimeException(e); } } public enum CStackMode { fp, lbr, no } public enum OutputType { text, collapsed, flamegraph, tree, jfr } public enum Direction { forward, reverse, both, } private static class ProfilerOptionsBuilder { private final OptionSet optionSet; private final StringBuilder profilerOptions; ProfilerOptionsBuilder(OptionSet optionSet) { this.optionSet = optionSet; this.profilerOptions = new StringBuilder(); } <T> void appendIfExists(OptionSpec<T> option) { if (optionSet.has(option)) { append(option); } } <T> void append(OptionSpec<T> option) { assert (option.options().size() == 1); String optionName = option.options().iterator().next(); separate(); profilerOptions.append(optionName); T arg = optionSet.valueOf(option); if (arg != null) { profilerOptions.append('=').append(arg); } } void appendRaw(String command) { separate(); profilerOptions.append(command); } private void separate() { if (profilerOptions.length() > 0) { profilerOptions.append(','); } } void appendIfTrue(OptionSpec<Boolean> option) { if (optionSet.has(option) && optionSet.valueOf(option)) { append(option); } } <T> void appendMulti(OptionSpec<T> option) { if (optionSet.has(option)) { assert (option.options().size() == 1); String optionName = option.options().iterator().next(); for (T value : optionSet.valuesOf(option)) { separate(); profilerOptions.append(optionName).append('=').append(value.toString()); } } } public String profilerOptions() { return profilerOptions.toString(); } } @Override public Collection<String> addJVMInvokeOptions(BenchmarkParams params) { return Collections.emptyList(); } @Override public Collection<String> addJVMOptions(BenchmarkParams params) { List<String> args = new ArrayList<>(); args.add("-XX:+UnlockDiagnosticVMOptions"); // Recommended option for async-profiler, enable automatically. args.add("-XX:+DebugNonSafepoints"); return args; } @Override public void beforeTrial(BenchmarkParams benchmarkParams) { } @Override public Collection<? extends Result> afterTrial(BenchmarkResult br, long pid, File stdOut, File stdErr) { return Collections.emptyList(); } @Override public boolean allowPrintOut() { return true; } @Override public boolean allowPrintErr() { return true; } @Override public String getDescription() { return "async-profiler profiler provider."; } // Made public so that power-users could can call filterThread from within the workload // to limit collection to a set of threads. This is useful for wall-clock profiling. // Adding support in JMH to pass the threads to profilers seems like an invasive change for // this niche use case. public static final class JavaApi { private static EnumSet<Thread.State> ignoredThreadStates = EnumSet.of(Thread.State.NEW, Thread.State.TERMINATED); private static JavaApi INSTANCE; public static JavaApi getInstance(String libraryFileName) { if (INSTANCE == null) { synchronized (AsyncProfiler.class) { INSTANCE = new JavaApi(libraryFileName); } } return INSTANCE; } public static JavaApi getInstance() { if (INSTANCE == null) { synchronized (AsyncProfiler.class) { INSTANCE = new JavaApi(); } } return INSTANCE; } private JavaApi(String libraryFileName) { System.load(libraryFileName); } private JavaApi() { System.loadLibrary("asyncProfiler"); } public String execute(String command) throws IOException { return execute0(command); } /** * Enable or disable profile collection for threads. * * @param thread The thread to enable or disable. * <code>null</code> indicates the current thread. * @param enable Whether to enable or disable. */ public void filterThread(Thread thread, boolean enable) { if (thread == null) { filterThread0(null, enable); } else { synchronized (thread) { Thread.State state = thread.getState(); if (!ignoredThreadStates.contains(state)) { filterThread0(thread, enable); } } } } // Loading async-profiler will automatically bind these native methods to the profiler implementation. private native void start0(String event, long interval, boolean reset) throws IllegalStateException; private native void stop0() throws IllegalStateException; private native String execute0(String command) throws IllegalArgumentException, IOException; private native long getSamples(); private native void filterThread0(Thread thread, boolean enable); } }
24,888
38.758786
156
java
jmh
jmh-master/jmh-core/src/main/java/org/openjdk/jmh/profile/ClassloaderProfiler.java
/* * Copyright (c) 2005, 2013, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package org.openjdk.jmh.profile; import org.openjdk.jmh.infra.BenchmarkParams; import org.openjdk.jmh.infra.IterationParams; import org.openjdk.jmh.results.*; import java.lang.management.ClassLoadingMXBean; import java.lang.management.ManagementFactory; import java.util.ArrayList; import java.util.Collection; import java.util.List; import java.util.concurrent.TimeUnit; public class ClassloaderProfiler implements InternalProfiler { private long loadedClasses; private long unloadedClasses; private long beforeTime; private long afterTime; @Override public String getDescription() { return "Classloader profiling via standard MBeans"; } @Override public void beforeIteration(BenchmarkParams benchmarkParams, IterationParams iterationParams) { ClassLoadingMXBean cl = ManagementFactory.getClassLoadingMXBean(); this.beforeTime = System.nanoTime(); try { loadedClasses = cl.getTotalLoadedClassCount(); } catch (UnsupportedOperationException e) { // do nothing } try { unloadedClasses = cl.getUnloadedClassCount(); } catch (UnsupportedOperationException e) { // do nothing } } @Override public Collection<? extends Result> afterIteration(BenchmarkParams benchmarkParams, IterationParams iterationParams, IterationResult result) { afterTime = System.nanoTime(); List<Result> results = new ArrayList<>(); ClassLoadingMXBean cl = ManagementFactory.getClassLoadingMXBean(); long allOps = result.getMetadata().getAllOps(); double time = 1.0 * TimeUnit.SECONDS.toNanos(1) / (afterTime - beforeTime); try { long loadedClassCount = cl.getTotalLoadedClassCount(); long loaded = loadedClassCount - loadedClasses; results.add(new ScalarResult(Defaults.PREFIX + "class.load", loaded / time, "classes/sec", AggregationPolicy.AVG)); results.add(new ScalarResult(Defaults.PREFIX + "class.load.norm", 1.0 * loaded / allOps, "classes/op", AggregationPolicy.AVG)); } catch (UnsupportedOperationException e) { // do nothing } try { long unloadedClassCount = cl.getUnloadedClassCount(); long unloaded = unloadedClassCount - unloadedClasses; results.add(new ScalarResult(Defaults.PREFIX + "class.unload", unloaded / time, "classes/sec", AggregationPolicy.AVG)); results.add(new ScalarResult(Defaults.PREFIX + "class.unload.norm", 1.0 * unloaded / allOps, "classes/op", AggregationPolicy.AVG)); } catch (UnsupportedOperationException e) { // do nothing } return results; } }
3,970
37.931373
146
java
jmh
jmh-master/jmh-core/src/main/java/org/openjdk/jmh/profile/CompilerProfiler.java
/* * Copyright (c) 2005, 2013, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package org.openjdk.jmh.profile; import org.openjdk.jmh.infra.BenchmarkParams; import org.openjdk.jmh.infra.IterationParams; import org.openjdk.jmh.results.*; import java.lang.management.CompilationMXBean; import java.lang.management.ManagementFactory; import java.util.Arrays; import java.util.Collection; import java.util.Collections; public class CompilerProfiler implements InternalProfiler { private long startCompTime; @Override public String getDescription() { return "JIT compiler profiling via standard MBeans"; } public CompilerProfiler() throws ProfilerException { CompilationMXBean comp = ManagementFactory.getCompilationMXBean(); if (!comp.isCompilationTimeMonitoringSupported()) { throw new ProfilerException("The MXBean is available, but compilation time monitoring is disabled."); } } @Override public void beforeIteration(BenchmarkParams benchmarkParams, IterationParams iterationParams) { CompilationMXBean comp = ManagementFactory.getCompilationMXBean(); try { startCompTime = comp.getTotalCompilationTime(); } catch (UnsupportedOperationException e) { // do nothing } } @Override public Collection<? extends Result> afterIteration(BenchmarkParams benchmarkParams, IterationParams iterationParams, IterationResult result) { CompilationMXBean comp = ManagementFactory.getCompilationMXBean(); try { long curTime = comp.getTotalCompilationTime(); return Arrays.asList( new ScalarResult(Defaults.PREFIX + "compiler.time.profiled", curTime - startCompTime, "ms", AggregationPolicy.SUM), new ScalarResult(Defaults.PREFIX + "compiler.time.total", curTime, "ms", AggregationPolicy.MAX) ); } catch (UnsupportedOperationException e) { return Collections.emptyList(); } } }
3,164
39.576923
146
java
jmh
jmh-master/jmh-core/src/main/java/org/openjdk/jmh/profile/DTraceAsmProfiler.java
/* * Copyright (c) 2014, 2015, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package org.openjdk.jmh.profile; import joptsimple.OptionException; import joptsimple.OptionParser; import joptsimple.OptionSpec; import org.openjdk.jmh.infra.BenchmarkParams; import org.openjdk.jmh.results.BenchmarkResult; import org.openjdk.jmh.results.Result; import org.openjdk.jmh.util.*; import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.io.IOException; import java.util.Collection; import java.util.Collections; import java.util.Map; import java.util.TreeMap; import java.util.concurrent.TimeUnit; /** * Mac OS X perfasm profiler based on DTrace "profile-n" provider which samples program counter by timer interrupt. * Due to DTrace limitations on Mac OS X target JVM cannot be run directly under DTrace control, so DTrace is run separately, * all processes are sampled and irrelevant samples are filtered out in {@link #readEvents(double, double)} stage. * Super user privileges are required in order to run DTrace. * <p> * If you see a lot of "[unknown]" regions in profile then you are probably hitting kernel code, kernel sampling is not yet supported. * * @author Tolstopyatov Vsevolod * @since 18/10/2017 */ public class DTraceAsmProfiler extends AbstractPerfAsmProfiler { private final long sampleFrequency; private volatile String pid; private volatile Process dtraceProcess; private OptionSpec<Long> optFrequency; public DTraceAsmProfiler(String initLine) throws ProfilerException { super(initLine, "sampled_pc"); // Check DTrace availability Collection<String> messages = Utils.tryWith("sudo", "-n", "dtrace", "-V"); if (!messages.isEmpty()) { throw new ProfilerException(messages.toString()); } try { sampleFrequency = set.valueOf(optFrequency); } catch (OptionException e) { throw new ProfilerException(e.getMessage()); } } @Override public void beforeTrial(BenchmarkParams params) { super.beforeTrial(params); } @Override public Collection<? extends Result> afterTrial(BenchmarkResult br, long pid, File stdOut, File stdErr) { if (pid == 0) { throw new IllegalStateException("DTrace needs the forked VM PID, but it is not initialized"); } // We cannot use Process.destroy, because it closes the streams right away. // Instead, deliver TERM by hand and wait for process to gracefully terminate. long dtracePid = Utils.getPid(dtraceProcess); if (dtracePid == 0) { throw new IllegalStateException("Cannot determine dtrace process PID"); } Collection<String> messages = Utils.tryWith("sudo", "-n", "kill", "-TERM", Long.toString(dtracePid)); if (!messages.isEmpty()) { throw new IllegalStateException(messages.toString()); } // Wait for dtrace to finish. try { int errcode = dtraceProcess.waitFor(); if (errcode != 0) { throw new IllegalStateException("Non-zero error code from dtrace: " + errcode); } } catch (InterruptedException e) { throw new IllegalStateException("Interrupted while waiting for profiler to stop"); } this.pid = String.valueOf(pid); return super.afterTrial(br, pid, stdOut, stdErr); } @Override public Collection<String> addJVMInvokeOptions(BenchmarkParams params) { dtraceProcess = Utils.runAsync("sudo", "-n", "dtrace", "-n", "profile-" + sampleFrequency + " /arg1/ { printf(\"%d 0x%lx %d\", pid, arg1, timestamp); ufunc(arg1)}", "-o", perfBinData.getAbsolutePath()); return Collections.emptyList(); } @Override public String getDescription() { return "DTrace profile provider + PrintAssembly Profiler"; } @Override protected void addMyOptions(OptionParser parser) { optFrequency = parser.accepts("frequency", "Sampling frequency. This is synonymous to profile-#") .withRequiredArg().ofType(Long.class).describedAs("freq").defaultsTo(1001L); } @Override protected void parseEvents() { // Do nothing because DTrace writes text output anyway } @Override protected PerfEvents readEvents(double skipMs, double lenMs) { long start = (long) skipMs; long end = (long) (skipMs + lenMs); try (FileReader fr = new FileReader(perfBinData.file()); BufferedReader reader = new BufferedReader(fr)) { Deduplicator<MethodDesc> dedup = new Deduplicator<>(); Multimap<MethodDesc, Long> methods = new HashMultimap<>(); Multiset<Long> events = new TreeMultiset<>(); long dtraceTimestampBase = 0L; String line; while ((line = reader.readLine()) != null) { // Filter out DTrace misc if (!line.contains(":profile")) { continue; } line = line.trim(); line = line.substring(line.indexOf(":profile")); String[] splits = line.split(" ", 5); if (splits.length < 2) { // Suspect completely corrupted line, skip continue; } String sampledPid = splits[1]; if (!sampledPid.equals(pid)) { continue; } // Sometimes DTrace ufunc fails and gives no information about symbols if (splits.length < 4) { continue; } long timestamp = Long.parseLong(splits[3]); if (dtraceTimestampBase == 0) { // Use first event timestamp as base for time comparison dtraceTimestampBase = timestamp; continue; } long elapsed = timestamp - dtraceTimestampBase; long elapsedMs = TimeUnit.NANOSECONDS.toMillis(elapsed); if (elapsedMs < start || elapsedMs > end) { continue; } long address = Long.decode(splits[2]); events.add(address); String methodLine = splits[4]; // JIT-compiled code has address instead of symbol information if (methodLine.startsWith("0x")) { continue; } String symbol = "[unknown]"; String[] methodSplit = methodLine.split("`"); String library = methodSplit[0]; if ("".equals(library)) { library = "[unknown]"; } if (methodSplit.length == 2) { symbol = methodSplit[1]; } methods.put(dedup.dedup(MethodDesc.nativeMethod(symbol, library)), address); } IntervalMap<MethodDesc> methodMap = new IntervalMap<>(); for (MethodDesc md : methods.keys()) { Collection<Long> longs = methods.get(md); methodMap.add(md, Utils.min(longs), Utils.max(longs)); } Map<String, Multiset<Long>> allEvents = new TreeMap<>(); assert requestedEventNames.size() == 1; allEvents.put(requestedEventNames.get(0), events); return new PerfEvents(requestedEventNames, allEvents, methodMap); } catch (IOException e) { throw new RuntimeException(e); } } @Override protected String perfBinaryExtension() { // DTrace produces human-readable txt return ".txt"; } }
8,981
36.26971
134
java
jmh
jmh-master/jmh-core/src/main/java/org/openjdk/jmh/profile/ExternalProfiler.java
/* * Copyright (c) 2005, 2013, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package org.openjdk.jmh.profile; import org.openjdk.jmh.infra.BenchmarkParams; import org.openjdk.jmh.results.BenchmarkResult; import org.openjdk.jmh.results.Result; import java.io.File; import java.util.Collection; /** * External profiler: profilers to be run outside of JVM. * * <p>External profilers usually call external tools to get the performance data. * It is futile to query any internal JVM facilities in external profiler * Java code, because it may not be executed in the benchmarked VM at all.</p> */ public interface ExternalProfiler extends Profiler { /** * Prepend JVM invocation with these commands. * * @param params benchmark parameters used for current launch * @return commands to prepend for JVM launch */ Collection<String> addJVMInvokeOptions(BenchmarkParams params); /** * Add JVM these options to the run. * * @param params benchmark parameters used for current launch * @return options to add to JVM launch */ Collection<String> addJVMOptions(BenchmarkParams params); /** * Run this code before starting the trial. This method will execute * before starting the benchmark JVM. * * @param benchmarkParams benchmark parameters used for current launch */ void beforeTrial(BenchmarkParams benchmarkParams); /** * Run this code after the trial is done. This method will execute * after benchmark JVM had stopped. * * @param br benchmark result that was the result of the trial * @param pid pid that the forked JVM had * @param stdOut file containing the standard output from the benchmark JVM * @param stdErr file containing the standard error from the benchmark JVM * @return profiler results */ Collection<? extends Result> afterTrial(BenchmarkResult br, long pid, File stdOut, File stdErr); /** * If target VM communicates with profiler with standard output, this method * can be used to shun the output to console. Profiler is responsible for consuming * the standard output and printing the relevant data from there. * * @return returns true, if profiler allows harness to print out the standard output */ boolean allowPrintOut(); /** * If target VM communicates with profiler with standard error, this method * can be used to shun the output to console. Profiler is responsible for consuming * the standard error and printing the relevant data from there. * * @return returns true, if profiler allows harness to print out the standard errpr */ boolean allowPrintErr(); }
3,855
38.752577
100
java
jmh
jmh-master/jmh-core/src/main/java/org/openjdk/jmh/profile/GCProfiler.java
/* * Copyright (c) 2005, 2022, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package org.openjdk.jmh.profile; import joptsimple.OptionException; import joptsimple.OptionParser; import joptsimple.OptionSet; import joptsimple.OptionSpec; import org.openjdk.jmh.infra.BenchmarkParams; import org.openjdk.jmh.infra.IterationParams; import org.openjdk.jmh.results.*; import org.openjdk.jmh.runner.options.IntegerValueConverter; import org.openjdk.jmh.util.HashMultiset; import org.openjdk.jmh.util.Multiset; import javax.management.ListenerNotFoundException; import javax.management.NotificationEmitter; import javax.management.NotificationListener; import javax.management.openmbean.CompositeData; import java.lang.management.*; import java.lang.reflect.Field; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.util.*; import java.util.concurrent.TimeUnit; public class GCProfiler implements InternalProfiler { private long beforeTime; private long beforeGCCount; private long beforeGCTime; private HotspotAllocationSnapshot beforeAllocated; private boolean churnEnabled; private boolean allocEnabled; private long churnWait; @Override public String getDescription() { return "GC profiling via standard MBeans"; } public GCProfiler(String initLine) throws ProfilerException { OptionParser parser = new OptionParser(); parser.formatHelpWith(new ProfilerOptionFormatter(PausesProfiler.class.getCanonicalName())); OptionSpec<Boolean> optAllocEnable = parser.accepts("alloc", "Enable GC allocation measurement.") .withRequiredArg().ofType(Boolean.class).describedAs("bool").defaultsTo(true); OptionSpec<Boolean> optChurnEnable = parser.accepts("churn", "Enable GC churn measurement.") .withRequiredArg().ofType(Boolean.class).describedAs("bool").defaultsTo(false); OptionSpec<Integer> optChurnWait = parser.accepts("churnWait", "Time to wait for churn notifications to arrive.") .withRequiredArg().withValuesConvertedBy(IntegerValueConverter.POSITIVE).describedAs("ms").defaultsTo(500); OptionSet set = ProfilerUtils.parseInitLine(initLine, parser); try { churnWait = set.valueOf(optChurnWait); churnEnabled = set.valueOf(optChurnEnable); allocEnabled = set.valueOf(optAllocEnable); } catch (OptionException e) { throw new ProfilerException(e.getMessage()); } if (churnEnabled) { if (!VMSupport.tryInitChurn()) { churnEnabled = false; } } if (allocEnabled) { if (!VMSupport.tryInitAlloc()) { allocEnabled = false; } } } @Override public void beforeIteration(BenchmarkParams benchmarkParams, IterationParams iterationParams) { if (churnEnabled) { VMSupport.startChurnProfile(); } long gcTime = 0; long gcCount = 0; for (GarbageCollectorMXBean bean : ManagementFactory.getGarbageCollectorMXBeans()) { gcCount += bean.getCollectionCount(); gcTime += bean.getCollectionTime(); } this.beforeGCCount = gcCount; this.beforeGCTime = gcTime; if (allocEnabled) { this.beforeAllocated = VMSupport.getSnapshot(); } this.beforeTime = System.nanoTime(); } @Override public Collection<? extends Result> afterIteration(BenchmarkParams benchmarkParams, IterationParams iterationParams, IterationResult iResult) { long afterTime = System.nanoTime(); if (churnEnabled) { VMSupport.finishChurnProfile(churnWait); } List<ScalarResult> results = new ArrayList<>(); long gcTime = 0; long gcCount = 0; for (GarbageCollectorMXBean bean : ManagementFactory.getGarbageCollectorMXBeans()) { gcCount += bean.getCollectionCount(); gcTime += bean.getCollectionTime(); } results.add(new ScalarResult( Defaults.PREFIX + "gc.count", gcCount - beforeGCCount, "counts", AggregationPolicy.SUM)); if (gcCount != beforeGCCount || gcTime != beforeGCTime) { results.add(new ScalarResult( Defaults.PREFIX + "gc.time", gcTime - beforeGCTime, "ms", AggregationPolicy.SUM)); } if (allocEnabled) { if (beforeAllocated != null) { HotspotAllocationSnapshot newSnapshot = VMSupport.getSnapshot(); long allocated = newSnapshot.difference(beforeAllocated); // When no allocations measured, we still need to report results to avoid user confusion results.add(new ScalarResult(Defaults.PREFIX + "gc.alloc.rate", (afterTime != beforeTime) ? 1.0 * allocated / 1024 / 1024 * TimeUnit.SECONDS.toNanos(1) / (afterTime - beforeTime) : Double.NaN, "MB/sec", AggregationPolicy.AVG)); if (allocated != 0) { long allOps = iResult.getMetadata().getAllOps(); results.add(new ScalarResult(Defaults.PREFIX + "gc.alloc.rate.norm", (allOps != 0) ? 1.0 * allocated / allOps : Double.NaN, "B/op", AggregationPolicy.AVG)); } } else { // When allocation profiling fails, make sure it is distinguishable in report results.add(new ScalarResult(Defaults.PREFIX + "gc.alloc.rate", Double.NaN, "MB/sec", AggregationPolicy.AVG)); } } if (churnEnabled) { Multiset<String> churn = VMSupport.getChurn(); for (String space : churn.keys()) { double churnRate = (afterTime != beforeTime) ? 1.0 * churn.count(space) * TimeUnit.SECONDS.toNanos(1) / (afterTime - beforeTime) / 1024 / 1024 : Double.NaN; double churnNorm = 1.0 * churn.count(space) / iResult.getMetadata().getAllOps(); String spaceName = space.replaceAll(" ", "_"); results.add(new ScalarResult( Defaults.PREFIX + "gc.churn." + spaceName + "", churnRate, "MB/sec", AggregationPolicy.AVG)); results.add(new ScalarResult( Defaults.PREFIX + "gc.churn." + spaceName + ".norm", churnNorm, "B/op", AggregationPolicy.AVG)); } } return results; } interface HotspotAllocationSnapshot { long difference(HotspotAllocationSnapshot before); } static class GlobalHotspotAllocationSnapshot implements HotspotAllocationSnapshot { private final long allocatedBytes; public GlobalHotspotAllocationSnapshot(long allocatedBytes) { this.allocatedBytes = allocatedBytes; } @Override public long difference(HotspotAllocationSnapshot before) { if (!(before instanceof GlobalHotspotAllocationSnapshot)) { throw new IllegalArgumentException(); } GlobalHotspotAllocationSnapshot other = (GlobalHotspotAllocationSnapshot) before; long beforeAllocs = other.allocatedBytes; if (allocatedBytes >= beforeAllocs) { return allocatedBytes - beforeAllocs; } else { // Do not allow negative values return 0; } } } static class PerThreadHotspotAllocationSnapshot implements HotspotAllocationSnapshot { private final long[] threadIds; private final long[] allocatedBytes; private PerThreadHotspotAllocationSnapshot(long[] threadIds, long[] allocatedBytes) { this.threadIds = threadIds; this.allocatedBytes = allocatedBytes; } /** * Estimates allocated bytes based on two snapshots. * The problem is threads can come and go while performing the benchmark, * thus we would miss allocations made in a thread that was created and died between the snapshots. * <p/> * <p>Current thread is intentionally excluded since it believed to execute jmh infrastructure code only. * * @return estimated number of allocated bytes between profiler calls */ public long difference(HotspotAllocationSnapshot before) { if (!(before instanceof PerThreadHotspotAllocationSnapshot)) { throw new IllegalArgumentException(); } PerThreadHotspotAllocationSnapshot other = (PerThreadHotspotAllocationSnapshot) before; HashMap<Long, Integer> prevIndex = new HashMap<>(); for (int i = 0; i < other.threadIds.length; i++) { long id = other.threadIds[i]; prevIndex.put(id, i); } long currentThreadId = Thread.currentThread().getId(); long allocated = 0; for (int i = 0; i < threadIds.length; i++) { long id = threadIds[i]; if (id == currentThreadId) { continue; } allocated += allocatedBytes[i]; Integer prev = prevIndex.get(id); if (prev != null) { allocated -= other.allocatedBytes[prev]; } } return allocated; } } /** * This class encapsulates any platform-specific functionality. It is supposed to gracefully * fail if some functionality is not available. This class resolves most special classes via * Reflection to enable building against a standard JDK. */ static class VMSupport { private static ThreadMXBean ALLOC_MX_BEAN; private static Method ALLOC_MX_BEAN_GETTER_PER_THREAD; private static Method ALLOC_MX_BEAN_GETTER_GLOBAL; private static NotificationListener LISTENER; private static Multiset<String> CHURN; private static boolean tryInitAlloc() { try { Class<?> internalIntf = Class.forName("com.sun.management.ThreadMXBean"); ThreadMXBean bean = ManagementFactory.getThreadMXBean(); if (!internalIntf.isAssignableFrom(bean.getClass())) { Class<?> pmo = Class.forName("java.lang.management.PlatformManagedObject"); Method m = ManagementFactory.class.getMethod("getPlatformMXBean", Class.class, pmo); bean = (ThreadMXBean) m.invoke(null, internalIntf); if (bean == null) { throw new UnsupportedOperationException("No way to access private ThreadMXBean"); } } ALLOC_MX_BEAN = bean; // See if global getter is available in this JVM try { ALLOC_MX_BEAN_GETTER_GLOBAL = internalIntf.getMethod("getTotalThreadAllocatedBytes"); getSnapshot(); return true; } catch (Exception e) { // Fall through } // See if per-thread getter is available in this JVM ALLOC_MX_BEAN_GETTER_PER_THREAD = internalIntf.getMethod("getThreadAllocatedBytes", long[].class); getSnapshot(); return true; } catch (Throwable e) { System.out.println("Allocation profiling is not available: " + e.getMessage()); } return false; } private static boolean tryInitChurn() { try { for (GarbageCollectorMXBean bean : ManagementFactory.getGarbageCollectorMXBeans()) { if (!(bean instanceof NotificationEmitter)) { throw new UnsupportedOperationException("GarbageCollectorMXBean cannot notify"); } } CHURN = new HashMultiset<>(); LISTENER = newListener(); return true; } catch (Throwable e) { System.out.println("Churn profiling is not available: " + e.getMessage()); } return false; } private static NotificationListener newListener() { try { final Class<?> infoKlass = Class.forName("com.sun.management.GarbageCollectionNotificationInfo"); final Field notifNameField = infoKlass.getField("GARBAGE_COLLECTION_NOTIFICATION"); final Method infoMethod = infoKlass.getMethod("from", CompositeData.class); final Method getGcInfo = infoKlass.getMethod("getGcInfo"); final Method getMemoryUsageBeforeGc = getGcInfo.getReturnType().getMethod("getMemoryUsageBeforeGc"); final Method getMemoryUsageAfterGc = getGcInfo.getReturnType().getMethod("getMemoryUsageAfterGc"); return (n, o) -> { try { if (n.getType().equals(notifNameField.get(null))) { Object info = infoMethod.invoke(null, n.getUserData()); Object gcInfo = getGcInfo.invoke(info); Map<String, MemoryUsage> mapBefore = (Map<String, MemoryUsage>) getMemoryUsageBeforeGc.invoke(gcInfo); Map<String, MemoryUsage> mapAfter = (Map<String, MemoryUsage>) getMemoryUsageAfterGc.invoke(gcInfo); for (Map.Entry<String, MemoryUsage> entry : mapAfter.entrySet()) { String name = entry.getKey(); MemoryUsage after = entry.getValue(); MemoryUsage before = mapBefore.get(name); long c = before.getUsed() - after.getUsed(); if (c > 0) { CHURN.add(name, c); } } } } catch (IllegalAccessException | InvocationTargetException e) { // Do nothing, counters would not get populated } }; } catch (Throwable e) { throw new IllegalStateException(e); } } public static HotspotAllocationSnapshot getSnapshot() { // Try the global getter first, if available if (ALLOC_MX_BEAN_GETTER_GLOBAL != null) { try { long allocatedBytes = (long) ALLOC_MX_BEAN_GETTER_GLOBAL.invoke(ALLOC_MX_BEAN); if (allocatedBytes == -1L) { throw new IllegalStateException("getTotalThreadAllocatedBytes is disabled"); } return new GlobalHotspotAllocationSnapshot(allocatedBytes); } catch (InvocationTargetException | IllegalAccessException e) { throw new IllegalStateException(e); } } // Fall back to per-thread getter long[] threadIds = ALLOC_MX_BEAN.getAllThreadIds(); try { long[] allocatedBytes = (long[]) ALLOC_MX_BEAN_GETTER_PER_THREAD.invoke(ALLOC_MX_BEAN, (Object) threadIds); return new PerThreadHotspotAllocationSnapshot(threadIds, allocatedBytes); } catch (InvocationTargetException | IllegalAccessException e) { throw new IllegalStateException(e); } } public static synchronized void startChurnProfile() { CHURN.clear(); try { for (GarbageCollectorMXBean bean : ManagementFactory.getGarbageCollectorMXBeans()) { ((NotificationEmitter) bean).addNotificationListener(LISTENER, null, null); } } catch (Exception e) { throw new IllegalStateException("Should not be here"); } } public static synchronized void finishChurnProfile(long churnWait) { // Notifications are asynchronous, need to wait a bit before deregistering the listener. try { Thread.sleep(churnWait); } catch (InterruptedException e) { // do not care } for (GarbageCollectorMXBean bean : ManagementFactory.getGarbageCollectorMXBeans()) { try { ((NotificationEmitter) bean).removeNotificationListener(LISTENER); } catch (ListenerNotFoundException e) { // Do nothing } } } public static synchronized Multiset<String> getChurn() { return (CHURN != null) ? CHURN : new HashMultiset<>(); } } }
18,569
41.39726
147
java
jmh
jmh-master/jmh-core/src/main/java/org/openjdk/jmh/profile/InternalProfiler.java
/* * Copyright (c) 2014, 2014, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package org.openjdk.jmh.profile; import org.openjdk.jmh.infra.BenchmarkParams; import org.openjdk.jmh.infra.IterationParams; import org.openjdk.jmh.results.IterationResult; import org.openjdk.jmh.results.Result; import java.util.Collection; /** * Internal profiler. * * <p>Internal profilers run in the benchmark JVM, and may query the internal * JVM facilities.</p> */ public interface InternalProfiler extends Profiler { /** * Run this code before starting the next benchmark iteration. * * @param benchmarkParams benchmark parameters used for current launch * @param iterationParams iteration parameters used for current launch */ void beforeIteration(BenchmarkParams benchmarkParams, IterationParams iterationParams); /** * Run this code after a benchmark iteration finished * * @param benchmarkParams benchmark parameters used for current launch * @param iterationParams iteration parameters used for current launch * @param result iteration result * @return profiler results */ Collection<? extends Result> afterIteration(BenchmarkParams benchmarkParams, IterationParams iterationParams, IterationResult result); }
2,421
38.704918
138
java
jmh
jmh-master/jmh-core/src/main/java/org/openjdk/jmh/profile/JavaFlightRecorderProfiler.java
/* * Copyright (c) 2020, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package org.openjdk.jmh.profile; import joptsimple.OptionException; import joptsimple.OptionParser; import joptsimple.OptionSet; import joptsimple.OptionSpec; import org.openjdk.jmh.infra.BenchmarkParams; import org.openjdk.jmh.infra.IterationParams; import org.openjdk.jmh.results.BenchmarkResult; import org.openjdk.jmh.results.IterationResult; import org.openjdk.jmh.results.Result; import org.openjdk.jmh.results.TextResult; import org.openjdk.jmh.runner.IterationType; import org.openjdk.jmh.util.JDKVersion; import org.openjdk.jmh.util.Utils; import java.io.File; import java.io.PrintWriter; import java.io.StringWriter; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.List; /** * A profiler based on Java Flight Recorder. * * @author Jason Zaugg */ public final class JavaFlightRecorderProfiler implements ExternalProfiler, InternalProfiler { private final boolean verbose; private final File outDir; private final boolean debugNonSafePoints; private final String configName; private final Collection<String> flightRecorderOptions = new ArrayList<>(); private PostProcessor postProcessor = null; private boolean measurementStarted = false; private int measurementIterationCount; private String profileName; private final List<File> generated = new ArrayList<>(); public JavaFlightRecorderProfiler(String initLine) throws ProfilerException { OptionParser parser = new OptionParser(); parser.formatHelpWith(new ProfilerOptionFormatter("jfr")); OptionSpec<String> optDir = parser.accepts("dir", "Output directory.") .withRequiredArg().ofType(String.class).describedAs("dir"); OptionSpec<String> optConfig = parser.accepts("configName", "Name of a predefined Flight Recorder configuration, e.g. profile or default") .withRequiredArg().ofType(String.class).describedAs("name").defaultsTo("profile"); OptionSpec<Boolean> optDebugNonSafePoints = parser.accepts("debugNonSafePoints", "Gather cpu samples asynchronously, rather than at the subsequent safepoint.") .withRequiredArg().ofType(Boolean.class).describedAs("bool").defaultsTo(true); OptionSpec<Integer> optStackDepth = parser.accepts("stackDepth", "Maximum number of stack frames collected for each event.") .withRequiredArg().ofType(Integer.class).describedAs("frames"); OptionSpec<String> optPostProcessor = parser.accepts("postProcessor", "The fully qualified name of a class that implements " + PostProcessor.class + ". " + "This must have a public, no-argument constructor.") .withRequiredArg().ofType(String.class).describedAs("fqcn"); OptionSpec<Boolean> optVerbose = parser.accepts("verbose", "Output the sequence of commands") .withRequiredArg().ofType(Boolean.class).defaultsTo(false).describedAs("bool"); OptionSet set = ProfilerUtils.parseInitLine(initLine, parser); try { this.debugNonSafePoints = optDebugNonSafePoints.value(set); this.configName = optConfig.value(set); if (set.has(optStackDepth)) { flightRecorderOptions.add("stackdepth=" + optStackDepth.value(set)); } verbose = optVerbose.value(set); if (!set.has(optDir)) { outDir = new File(System.getProperty("user.dir")); } else { outDir = new File(set.valueOf(optDir)); } if (set.has(optPostProcessor)) { try { ClassLoader loader = Thread.currentThread().getContextClassLoader(); Class<?> postProcessorClass = loader.loadClass(optPostProcessor.value(set)); postProcessor = (PostProcessor) postProcessorClass.getDeclaredConstructor().newInstance(); } catch (ReflectiveOperationException e) { throw new ProfilerException(e); } } } catch (OptionException e) { throw new ProfilerException(e.getMessage()); } } @Override public void beforeIteration(BenchmarkParams benchmarkParams, IterationParams iterationParams) { if (iterationParams.getType() == IterationType.MEASUREMENT) { if (!measurementStarted) { profileName = benchmarkParams.id(); execute(benchmarkParams.getJvm(), "JFR.start", Collections.singletonList("settings=" + configName)); measurementStarted = true; } } } @Override public Collection<? extends Result> afterIteration(BenchmarkParams benchmarkParams, IterationParams iterationParams, IterationResult iterationResult) { if (iterationParams.getType() == IterationType.MEASUREMENT) { measurementIterationCount += 1; if (measurementIterationCount == iterationParams.getCount()) { File trialOutDir = createTrialOutDir(benchmarkParams); File jfrFile = new File(trialOutDir, "profile.jfr"); String filenameOption = "filename=" + jfrFile.getAbsolutePath(); execute(benchmarkParams.getJvm(), "JFR.stop", Collections.singletonList(filenameOption)); generated.add(jfrFile); if (postProcessor != null) { generated.addAll(postProcessor.postProcess(benchmarkParams, jfrFile)); } return Collections.singletonList(result()); } } return Collections.emptyList(); } private TextResult result() { StringWriter output = new StringWriter(); PrintWriter pw = new PrintWriter(output); pw.println("JFR profiler results:"); for (File file : generated) { pw.print(" "); pw.println(file.getPath()); } pw.flush(); pw.close(); return new TextResult(output.toString(), "jfr"); } private File createTrialOutDir(BenchmarkParams benchmarkParams) { String fileName = benchmarkParams.id(); File trialOutDir = new File(this.outDir, fileName); trialOutDir.mkdirs(); return trialOutDir; } private void execute(String jvm, String cmd, Collection<String> options) { long pid = Utils.getPid(); ArrayList<String> fullCommand = new ArrayList<>(); fullCommand.add(findJcmd(jvm).getAbsolutePath()); fullCommand.add(String.valueOf(pid)); fullCommand.add(cmd); fullCommand.add("name=" + profileName); fullCommand.addAll(options); if (verbose) { System.out.println("[jfr] " + fullCommand); } // TODO Use JMX to control FlightRecorder when the baseline of JDK support in JMH // advances to a version with that included. Collection<String> errorOutput = Utils.tryWith(fullCommand.toArray(new String[0])); if (!errorOutput.isEmpty()) { throw new RuntimeException("Error executing: " + fullCommand + System.lineSeparator() + Utils.join(errorOutput, System.lineSeparator())); } } private File findJcmd(String jvm) { // Try 1: same directory as JVM binary File bin = new File(jvm).getParentFile(); { File jcmd = new File(bin, "jcmd" + (Utils.isWindows() ? ".exe" : "")); if (jcmd.exists()) { return jcmd; } } // Try 2: parent bin/ directory { final String s = File.separator; File jcmd = new File(bin, ".." + s + ".." + s + "bin" + s + "jcmd" + (Utils.isWindows() ? ".exe" : "")); if (jcmd.exists()) { return jcmd; } } // No dice. throw new IllegalStateException("Cannot find jcmd anywhere"); } @Override public Collection<String> addJVMInvokeOptions(BenchmarkParams params) { return Collections.emptyList(); } @Override public Collection<String> addJVMOptions(BenchmarkParams params) { List<String> args = new ArrayList<>(); if (debugNonSafePoints) { args.add("-XX:+UnlockDiagnosticVMOptions"); args.add("-XX:+DebugNonSafepoints"); } if (!flightRecorderOptions.isEmpty()) { args.add("-XX:FlightRecorderOptions=" + Utils.join(flightRecorderOptions, ",")); } // JDK 13+ does not need need the opt-in if (JDKVersion.parseMajor(params.getJdkVersion()) < 13) { args.add("-XX:+FlightRecorder"); } return args; } @Override public void beforeTrial(BenchmarkParams benchmarkParams) { } @Override public Collection<? extends Result> afterTrial(BenchmarkResult br, long pid, File stdOut, File stdErr) { return Collections.emptyList(); } @Override public boolean allowPrintOut() { return true; } @Override public boolean allowPrintErr() { return true; } @Override public String getDescription() { return "Java Flight Recorder profiler"; } public interface PostProcessor { List<File> postProcess(BenchmarkParams benchmarkParams, File jfrFile); } }
10,617
37.751825
120
java
jmh
jmh-master/jmh-core/src/main/java/org/openjdk/jmh/profile/LinuxPerfAsmProfiler.java
/* * Copyright (c) 2014, 2014, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package org.openjdk.jmh.profile; import joptsimple.OptionException; import joptsimple.OptionParser; import joptsimple.OptionSpec; import org.openjdk.jmh.infra.BenchmarkParams; import org.openjdk.jmh.util.*; import java.io.BufferedReader; import java.io.FileOutputStream; import java.io.FileReader; import java.io.IOException; import java.math.BigInteger; import java.util.*; public class LinuxPerfAsmProfiler extends AbstractPerfAsmProfiler { private final String sampleFrequency; private OptionSpec<String> optFrequency; public LinuxPerfAsmProfiler(String initLine) throws ProfilerException { super(initLine, "cycles"); String[] senseCmd = { PerfSupport.PERF_EXEC, "stat", "--event", Utils.join(requestedEventNames, ","), "--log-fd", "2", "echo", "1" }; Collection<String> failMsg = Utils.tryWith(senseCmd); if (!failMsg.isEmpty()) { throw new ProfilerException(failMsg.toString()); } Collection<String> passMsg = Utils.runWith(senseCmd); for (String ev : requestedEventNames) { if (PerfSupport.containsUnsupported(passMsg, ev)) { throw new ProfilerException("Unsupported event: " + ev); } } try { sampleFrequency = set.valueOf(optFrequency); } catch (OptionException e) { throw new ProfilerException(e.getMessage()); } } @Override protected void addMyOptions(OptionParser parser) { optFrequency = parser.accepts("frequency", "Sampling frequency, synonymous to perf record --freq #; " + "use \"max\" for highest sampling rate possible on the system.") .withRequiredArg().ofType(String.class).describedAs("freq").defaultsTo("1000"); } @Override public Collection<String> addJVMInvokeOptions(BenchmarkParams params) { return Arrays.asList(PerfSupport.PERF_EXEC, "record", "--freq", String.valueOf(sampleFrequency), "--event", Utils.join(requestedEventNames, ","), "--output", perfBinData.getAbsolutePath()); } @Override public String getDescription() { return "Linux perf + PrintAssembly Profiler"; } @Override protected void parseEvents() { try (FileOutputStream fos = new FileOutputStream(perfParsedData.file())) { ProcessBuilder pb = new ProcessBuilder(PerfSupport.PERF_EXEC, "script", "--fields", "time,event,ip,sym,dso", "--input", perfBinData.getAbsolutePath()); Process p = pb.start(); // drain streams, else we might lock up InputStreamDrainer errDrainer = new InputStreamDrainer(p.getErrorStream(), fos); InputStreamDrainer outDrainer = new InputStreamDrainer(p.getInputStream(), fos); errDrainer.start(); outDrainer.start(); p.waitFor(); errDrainer.join(); outDrainer.join(); } catch (IOException | InterruptedException ex) { throw new IllegalStateException(ex); } } static PerfLine parsePerfLine(String line) { if (line.startsWith("#")) { return null; } // Demangled symbol names can contain spaces, so we need to parse the lines // in a complicated manner. Using regexps will not solve this without sacrificing // lots of performance, so we need to get tricky. // // We are forcing perf to print: time event ip sym dso // // 328992.235251: instructions: 7fa85da61a09 match_symbol (/lib/x86_64-linux-gnu/ld-2.23.so) // // Remove excess spaces int lastLength = -1; while (line.length() != lastLength) { lastLength = line.length(); line = line.replace(" ", " "); } // Chomp the time int timeIdx = line.indexOf(": "); if (timeIdx == -1) return null; String strTime = line.substring(0, timeIdx); line = line.substring(timeIdx + 2); double time; try { time = Double.parseDouble(strTime); } catch (NumberFormatException e) { return null; } // Chomp the library, handling spaces properly: int libIdx = line.lastIndexOf(" ("); if (libIdx == -1) return null; String lib = line.substring(libIdx); lib = lib.substring(lib.lastIndexOf("/") + 1).replace("(", "").replace(")", ""); line = line.substring(0, libIdx); // Chomp the event name: int evIdx = line.indexOf(": "); if (evIdx == -1) return null; String evName = line.substring(0, evIdx); int tagIdx = evName.lastIndexOf(":"); if (tagIdx != -1) { evName = evName.substring(0, tagIdx); } line = line.substring(evIdx + 2); // Chomp the addr: int addrIdx = line.indexOf(" "); if (addrIdx == -1) return null; String strAddr = line.substring(0, addrIdx); line = line.substring(addrIdx + 1); // Try to parse the positive address lightly first. // If that fails, try to parse the negative address. // If that fails as well, then address is unresolvable. long addr; try { addr = Long.parseLong(strAddr, 16); } catch (NumberFormatException e) { try { addr = new BigInteger(strAddr, 16).longValue(); if (addr < 0L && lib.contains("unknown")) { lib = "kernel"; } } catch (NumberFormatException e1) { addr = 0L; } } // Whatever is left is symbol: String symbol = line; return new PerfLine(time, evName, addr, symbol, lib); } static class PerfLine { final double time; final String event; final long addr; final String symbol; final String lib; public PerfLine(double time, String event, long addr, String symbol, String lib) { this.time = time; this.event = event; this.addr = addr; this.symbol = symbol; this.lib = lib; } public double time() { return time; } public String eventName() { return event; } public long addr() { return addr; } public String symbol() { return symbol; } public String lib() { return lib; } } @Override protected PerfEvents readEvents(double skipMs, double lenMs) { double readFrom = skipMs / 1000D; double readTo = (skipMs + lenMs) / 1000D; List<String> evNames = stripEventNames(requestedEventNames); try (FileReader fr = new FileReader(perfParsedData.file()); BufferedReader reader = new BufferedReader(fr)) { Deduplicator<MethodDesc> dedup = new Deduplicator<>(); Multimap<MethodDesc, Long> methods = new HashMultimap<>(); Map<String, Multiset<Long>> events = new LinkedHashMap<>(); for (String evName : evNames) { events.put(evName, new TreeMultiset<>()); } Double startTime = null; String line; while ((line = reader.readLine()) != null) { PerfLine perfline = parsePerfLine(line); if (perfline == null) { continue; } if (startTime == null) { startTime = perfline.time(); } else { if (perfline.time() - startTime < readFrom) { continue; } if (perfline.time() - startTime > readTo) { continue; } } Multiset<Long> evs = events.get(perfline.eventName()); if (evs == null) { // we are not prepared to handle this event, skip continue; } evs.add(perfline.addr()); MethodDesc desc = dedup.dedup(MethodDesc.nativeMethod(perfline.symbol(), perfline.lib())); methods.put(desc, perfline.addr()); } IntervalMap<MethodDesc> methodMap = new IntervalMap<>(); for (MethodDesc md : methods.keys()) { Collection<Long> addrs = methods.get(md); methodMap.add(md, Utils.min(addrs), Utils.max(addrs)); } return new PerfEvents(evNames, events, methodMap); } catch (IOException e) { throw new RuntimeException(e); } } @Override protected String perfBinaryExtension() { return ".perfbin"; } @Override protected List<String> stripEventNames(List<String> events) { return stripPerfEventNames(events); } static List<String> stripPerfEventNames(List<String> events) { List<String> res = new ArrayList<>(); for (String ev : events) { int tagIdx = ev.indexOf(':'); if (tagIdx != -1) { res.add(ev.substring(0, tagIdx)); } else { res.add(ev); } } return res; } }
10,580
33.132258
197
java
jmh
jmh-master/jmh-core/src/main/java/org/openjdk/jmh/profile/LinuxPerfC2CProfiler.java
/* * Copyright (c) 2020, 2020, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package org.openjdk.jmh.profile; import org.openjdk.jmh.infra.BenchmarkParams; import org.openjdk.jmh.results.BenchmarkResult; import org.openjdk.jmh.results.Result; import org.openjdk.jmh.results.TextResult; import org.openjdk.jmh.util.FileUtils; import org.openjdk.jmh.util.TempFile; import org.openjdk.jmh.util.Utils; import java.io.File; import java.io.IOException; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.concurrent.TimeUnit; public final class LinuxPerfC2CProfiler implements ExternalProfiler { protected final TempFile perfBinData; public LinuxPerfC2CProfiler() throws ProfilerException { Collection<String> failMsg = Utils.tryWith(PerfSupport.PERF_EXEC, "c2c", "record", "echo", "1"); if (!failMsg.isEmpty()) { throw new ProfilerException(failMsg.toString()); } try { perfBinData = FileUtils.weakTempFile("perf-c2c-bin"); } catch (IOException e) { throw new ProfilerException(e); } } @Override public Collection<String> addJVMInvokeOptions(BenchmarkParams params) { long delay = TimeUnit.NANOSECONDS.toMillis(params.getWarmup().getCount() * params.getWarmup().getTime().convertTo(TimeUnit.NANOSECONDS)) + TimeUnit.SECONDS.toMillis(1); // loosely account for the JVM lag return Arrays.asList("perf", "c2c", "record", "-o", perfBinData.getAbsolutePath(), "--", "--delay", String.valueOf(delay)); } @Override public Collection<String> addJVMOptions(BenchmarkParams params) { return Collections.emptyList(); } @Override public void beforeTrial(BenchmarkParams params) {} @Override public Collection<? extends Result> afterTrial(BenchmarkResult br, long pid, File stdOut, File stdErr) { try { Process process = new ProcessBuilder("perf", "c2c", "report", "--stats", "-i", perfBinData.getAbsolutePath()) .redirectErrorStream(true) .start(); Collection<String> lines = FileUtils.readAllLines(process.getInputStream()); String out = Utils.join(lines, System.lineSeparator()); return Collections.singleton(new TextResult(out, "perfc2c")); } catch (IOException e) { throw new RuntimeException(e); } } @Override public boolean allowPrintOut() { return false; } @Override public boolean allowPrintErr() { return false; } @Override public String getDescription() { return "Linux perf c2c profiler"; } }
3,868
35.158879
131
java
jmh
jmh-master/jmh-core/src/main/java/org/openjdk/jmh/profile/LinuxPerfNormProfiler.java
/* * Copyright (c) 2014, 2014, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package org.openjdk.jmh.profile; import joptsimple.OptionException; import joptsimple.OptionParser; import joptsimple.OptionSet; import joptsimple.OptionSpec; import org.openjdk.jmh.infra.BenchmarkParams; import org.openjdk.jmh.results.*; import org.openjdk.jmh.util.*; import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.io.IOException; import java.text.NumberFormat; import java.text.ParseException; import java.util.*; public class LinuxPerfNormProfiler implements ExternalProfiler { /** This is a non-exhaustive list of events we care about. */ private static final String[] interestingEvents = new String[]{ "cycles", "instructions", "branches", "branch-misses", "L1-dcache-loads", "L1-dcache-load-misses", "L1-dcache-stores", "L1-dcache-store-misses", "L1-icache-loads", "L1-icache-load-misses", "LLC-loads", "LLC-load-misses", "LLC-stores", "LLC-store-misses", "dTLB-loads", "dTLB-load-misses", "dTLB-stores", "dTLB-store-misses", "iTLB-loads", "iTLB-load-misses", "stalled-cycles-frontend", "stalled-cycles-backend", }; private final int delayMs; private final int lengthMs; private final boolean useDefaultStats; private final long highPassFilter; private final int incrementInterval; private final boolean isIncrementable; private final Collection<String> supportedEvents = new ArrayList<>(); public LinuxPerfNormProfiler(String initLine) throws ProfilerException { OptionParser parser = new OptionParser(); parser.formatHelpWith(new ProfilerOptionFormatter("perfnorm")); OptionSpec<String> optEvents = parser.accepts("events", "Events to gather.") .withRequiredArg().ofType(String.class).withValuesSeparatedBy(",").describedAs("event+"); OptionSpec<Integer> optDelay = parser.accepts("delay", "Delay collection for a given time, in milliseconds; -1 to detect automatically.") .withRequiredArg().ofType(Integer.class).describedAs("ms").defaultsTo(-1); OptionSpec<Integer> optLength = parser.accepts("length", "Do the collection for a given time, in milliseconds; -1 to detect automatically.") .withRequiredArg().ofType(Integer.class).describedAs("ms").defaultsTo(-1); OptionSpec<Integer> optIncrementInterval = parser.accepts("interval", "The interval between incremental updates from a concurrently running perf. " + "Lower values may improve accuracy, while increasing the profiling overhead.") .withRequiredArg().ofType(Integer.class).describedAs("ms").defaultsTo(100); OptionSpec<Long> optHighPassFilter = parser.accepts("highPassFilter", "Ignore event increments larger that this.") .withRequiredArg().ofType(Long.class).describedAs("#").defaultsTo(100_000_000_000L); OptionSpec<Boolean> optDefaultStat = parser.accepts("useDefaultStat", "Use \"perf stat -d -d -d\" instead of explicit counter list.") .withRequiredArg().ofType(Boolean.class).describedAs("bool").defaultsTo(false); OptionSet set = ProfilerUtils.parseInitLine(initLine, parser); Collection<String> userEvents; try { delayMs = set.valueOf(optDelay); lengthMs = set.valueOf(optLength); incrementInterval = set.valueOf(optIncrementInterval); highPassFilter = set.valueOf(optHighPassFilter); useDefaultStats = set.valueOf(optDefaultStat); userEvents = set.valuesOf(optEvents); } catch (OptionException e) { throw new ProfilerException(e.getMessage()); } Collection<String> msgs = Utils.tryWith(PerfSupport.PERF_EXEC, "stat", "--log-fd", "2", "--field-separator", ",", "echo", "1"); if (!msgs.isEmpty()) { throw new ProfilerException(msgs.toString()); } Collection<String> incremental = Utils.tryWith(PerfSupport.PERF_EXEC, "stat", "--log-fd", "2", "--field-separator", ",", "--interval-print", String.valueOf(incrementInterval), "echo", "1"); isIncrementable = incremental.isEmpty(); Collection<String> candidateEvents = new ArrayList<>(); if (userEvents != null) { for (String ev : userEvents) { if (ev.trim().isEmpty()) continue; candidateEvents.add(ev); } } if (supportedEvents.isEmpty()) { candidateEvents.addAll(Arrays.asList(interestingEvents)); } for (String ev : candidateEvents) { String[] senseCmd = { PerfSupport.PERF_EXEC, "stat", "--log-fd", "2", "--field-separator", ",", "--event", ev, "echo", "1" }; Collection<String> res = Utils.tryWith(senseCmd); if (res.isEmpty()) { Collection<String> out = Utils.runWith(senseCmd); if (!PerfSupport.containsUnsupported(out, ev)) { supportedEvents.add(ev); } } } if (!useDefaultStats && supportedEvents.isEmpty()) { throw new ProfilerException("No supported events."); } } @Override public Collection<String> addJVMInvokeOptions(BenchmarkParams params) { List<String> cmd = new ArrayList<>(); if (useDefaultStats) { cmd.addAll(Arrays.asList(PerfSupport.PERF_EXEC, "stat", "--log-fd", "2", "--field-separator", ",", "--detailed", "--detailed", "--detailed")); } else { cmd.addAll(Arrays.asList(PerfSupport.PERF_EXEC, "stat", "--log-fd", "2", "--field-separator", ",", "--event", Utils.join(supportedEvents, ","))); } if (isIncrementable) { cmd.addAll(Arrays.asList("-I", String.valueOf(incrementInterval))); } return cmd; } @Override public Collection<String> addJVMOptions(BenchmarkParams params) { return Collections.emptyList(); } @Override public void beforeTrial(BenchmarkParams params) { // do nothing } @Override public Collection<? extends Result> afterTrial(BenchmarkResult br, long pid, File stdOut, File stdErr) { return process(br, stdOut, stdErr); } @Override public boolean allowPrintOut() { return true; } @Override public boolean allowPrintErr() { return false; } @Override public String getDescription() { return "Linux perf statistics, normalized by operation count"; } private Collection<? extends Result> process(BenchmarkResult br, File stdOut, File stdErr) { Multiset<String> events = new HashMultiset<>(); try (FileReader fr = new FileReader(stdErr); BufferedReader reader = new BufferedReader(fr)) { long skipMs; if (delayMs == -1) { // not set skipMs = ProfilerUtils.measurementDelayMs(br); } else { skipMs = delayMs; } double lenMs; if (lengthMs == -1) { // not set lenMs = ProfilerUtils.measuredTimeMs(br); } else { lenMs = lengthMs; } double readFrom = skipMs / 1000D; double softTo = (skipMs + lenMs) / 1000D; double readTo = (skipMs + lenMs + incrementInterval) / 1000D; NumberFormat nf = NumberFormat.getInstance(); String line; nextline: while ((line = reader.readLine()) != null) { if (line.startsWith("#")) continue; if (isIncrementable) { String[] split = line.split(","); String time; String count; String event; if (split.length == 3) { // perf 3.13: time,count,event time = split[0].trim(); count = split[1].trim(); event = split[2].trim(); } else if (split.length >= 4) { // perf >3.13: time,count,<other>,event,<others> time = split[0].trim(); count = split[1].trim(); event = split[3].trim(); } else { // Malformed line, ignore continue nextline; } double multiplier = 1D; try { double timeSec = nf.parse(time).doubleValue(); if (timeSec < readFrom) { // warmup, ignore continue nextline; } if (timeSec > readTo) { // post-run, ignore continue nextline; } // Handle partial events: double intervalSec = incrementInterval / 1000D; if (timeSec - intervalSec < readFrom) { // Event _starts_ before the measurement window // .............[============|============ // readFrom timeSec // [<----------------->| // event // incrementInterval // // Only count the tail after readFrom: multiplier = (timeSec - readFrom) / intervalSec; } if (timeSec > softTo) { // Event is past the measurement window // =============].............|............ // softTo timeSec // [<----------------->| // event // incrementInterval // // Only count the head before softTo: multiplier = 1 - (timeSec - softTo) / intervalSec; } // Defensive, keep multiplier in bounds: multiplier = Math.max(1D, Math.min(0D, multiplier)); } catch (ParseException e) { // don't care then, continue continue nextline; } try { long lValue = nf.parse(count).longValue(); if (lValue > highPassFilter) { // anomalous value, pretend we did not see it continue nextline; } events.add(event, (long) (lValue * multiplier)); } catch (ParseException e) { // do nothing, continue continue nextline; } } else { int idx = line.lastIndexOf(","); // Malformed line, ignore if (idx == -1) continue nextline; String count = line.substring(0, idx).trim(); String event = line.substring(idx + 1).trim(); try { long lValue = nf.parse(count).longValue(); events.add(event, lValue); } catch (ParseException e) { // do nothing, continue continue nextline; } } } if (!isIncrementable) { System.out.println(); System.out.println(); System.out.println("WARNING: Your system uses old \"perf\", which cannot print data incrementally (-I).\n" + "Therefore, perf performance data includes benchmark warmup."); } long totalOpts; BenchmarkResultMetaData md = br.getMetadata(); if (md != null) { if (isIncrementable) { totalOpts = md.getMeasurementOps(); } else { totalOpts = md.getWarmupOps() + md.getMeasurementOps(); } Collection<Result> results = new ArrayList<>(); for (String key : events.keys()) { results.add(new PerfResult(key, "#/op", events.count(key) * 1.0 / totalOpts)); } // Also figure out IPC/CPI, if enough counters available: { long c1 = events.count("cycles"); long c2 = events.count("cycles:u"); long i1 = events.count("instructions"); long i2 = events.count("instructions:u"); long cycles = (c1 != 0) ? c1 : c2; long instructions = (i1 != 0) ? i1 : i2; if (cycles != 0 && instructions != 0) { results.add(new PerfResult("CPI", "clks/insn", 1.0 * cycles / instructions)); results.add(new PerfResult("IPC", "insns/clk", 1.0 * instructions / cycles)); } } return results; } else { return Collections.singleton(new PerfResult("N/A", "", Double.NaN)); } } catch (IOException e) { throw new IllegalStateException(e); } } static class PerfResult extends ScalarResult { private static final long serialVersionUID = -1262685915873231436L; public PerfResult(String key, String unit, double value) { super(key, value, unit, AggregationPolicy.AVG); } @Override public String extendedInfo() { // omit printing in extended info return ""; } } }
15,519
39.311688
197
java
jmh
jmh-master/jmh-core/src/main/java/org/openjdk/jmh/profile/LinuxPerfProfiler.java
/* * Copyright (c) 2014, 2014, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package org.openjdk.jmh.profile; import joptsimple.OptionException; import joptsimple.OptionParser; import joptsimple.OptionSet; import joptsimple.OptionSpec; import org.openjdk.jmh.infra.BenchmarkParams; import org.openjdk.jmh.results.*; import org.openjdk.jmh.util.ScoreFormatter; import org.openjdk.jmh.util.Utils; import java.io.*; import java.text.NumberFormat; import java.text.ParseException; import java.util.Arrays; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.List; import java.util.concurrent.TimeUnit; import java.util.regex.Matcher; import java.util.regex.Pattern; public class LinuxPerfProfiler implements ExternalProfiler { private final boolean isDelayed; private final int delayMs; private final List<String> events; public LinuxPerfProfiler(String initLine) throws ProfilerException { OptionParser parser = new OptionParser(); parser.formatHelpWith(new ProfilerOptionFormatter("perf")); OptionSpec<Integer> optDelay = parser.accepts("delay", "Delay collection for a given time, in milliseconds; -1 to detect automatically.") .withRequiredArg().ofType(Integer.class).describedAs("ms").defaultsTo(-1); OptionSpec<String> optEvents = parser.accepts("events", "Events to gather.") .withRequiredArg().ofType(String.class).withValuesSeparatedBy(",").describedAs("event"); OptionSet set = ProfilerUtils.parseInitLine(initLine, parser); try { events = set.valuesOf(optEvents); delayMs = set.valueOf(optDelay); } catch (OptionException e) { throw new ProfilerException(e.getMessage()); } Collection<String> msgs = Utils.tryWith(PerfSupport.PERF_EXEC, "stat", "--log-fd", "2", "echo", "1"); if (!msgs.isEmpty()) { throw new ProfilerException(msgs.toString()); } Collection<String> delay = Utils.tryWith(PerfSupport.PERF_EXEC, "stat", "--log-fd", "2", "--delay", "1", "echo", "1"); isDelayed = delay.isEmpty(); } @Override public Collection<String> addJVMInvokeOptions(BenchmarkParams params) { long delay; if (delayMs == -1) { // not set delay = TimeUnit.NANOSECONDS.toMillis(params.getWarmup().getCount() * params.getWarmup().getTime().convertTo(TimeUnit.NANOSECONDS)) + TimeUnit.SECONDS.toMillis(1); // loosely account for the JVM lag } else { delay = delayMs; } List<String> invokeOptions = new ArrayList<>(Arrays.asList(PerfSupport.PERF_EXEC, "stat", "--log-fd", "2", "--detailed", "--detailed", "--detailed")); if (isDelayed) { invokeOptions.add("--delay"); invokeOptions.add(String.valueOf(delay)); } if (!events.isEmpty()) { invokeOptions.add("-e"); invokeOptions.add(Utils.join(events, ",")); } return invokeOptions; } @Override public Collection<String> addJVMOptions(BenchmarkParams params) { return Collections.emptyList(); } @Override public void beforeTrial(BenchmarkParams params) { // do nothing } @Override public Collection<? extends Result> afterTrial(BenchmarkResult br, long pid, File stdOut, File stdErr) { PerfResult result = process(stdOut, stdErr); return Collections.singleton(result); } @Override public boolean allowPrintOut() { return true; } @Override public boolean allowPrintErr() { return false; } @Override public String getDescription() { return "Linux perf Statistics"; } private PerfResult process(File stdOut, File stdErr) { StringWriter sw = new StringWriter(); PrintWriter pw = new PrintWriter(sw); final Pattern hashLinePattern = Pattern.compile("(.*)#(.*)"); try (FileReader fr = new FileReader(stdErr); BufferedReader reader = new BufferedReader(fr)) { long cycles = 0; long insns = 0; boolean printing = false; String line; while ((line = reader.readLine()) != null) { if (printing) { pw.println(line); } if (line.contains("Performance counter stats")) { printing = true; } Matcher m = hashLinePattern.matcher(line); if (m.matches()) { String pair = m.group(1).trim(); if (pair.contains(" cycles")) { try { cycles = NumberFormat.getInstance().parse(pair.split("[ ]+")[0]).longValue(); } catch (ParseException e) { // do nothing, processing code will handle } } if (line.contains(" instructions")) { try { insns = NumberFormat.getInstance().parse(pair.split("[ ]+")[0]).longValue(); } catch (ParseException e) { // do nothing, processing code will handle } } } } if (!isDelayed) { pw.println(); pw.println("WARNING: Your system uses old \"perf\", which can not delay data collection.\n" + "Therefore, perf performance data includes benchmark warmup."); } pw.flush(); pw.close(); return new PerfResult( sw.toString(), cycles, insns ); } catch (IOException e) { throw new IllegalStateException(e); } } static class PerfResult extends Result<PerfResult> { private static final long serialVersionUID = -1262685915873231436L; private final String output; private final long cycles; private final long instructions; public PerfResult(String output, long cycles, long instructions) { super(ResultRole.SECONDARY, Defaults.PREFIX + "perf", of(Double.NaN), "---", AggregationPolicy.AVG); this.output = output; this.cycles = cycles; this.instructions = instructions; } @Override protected Aggregator<PerfResult> getThreadAggregator() { return new PerfResultAggregator(); } @Override protected Aggregator<PerfResult> getIterationAggregator() { return new PerfResultAggregator(); } @Override protected Collection<? extends Result> getDerivativeResults() { List<Result> res = new ArrayList<>(); if (cycles != 0 && instructions != 0) { res.add(new ScalarDerivativeResult(Defaults.PREFIX + "ipc", 1.0 * instructions / cycles, "insns/clk", AggregationPolicy.AVG)); res.add(new ScalarDerivativeResult(Defaults.PREFIX + "cpi", 1.0 * cycles / instructions, "clks/insn", AggregationPolicy.AVG)); } return res; } @Override public String toString() { if (cycles != 0 && instructions != 0) { return String.format("%s IPC, %s CPI", ScoreFormatter.format(1.0 * instructions / cycles), ScoreFormatter.format(1.0 * cycles / instructions)); } else { return "N/A"; } } @Override public String extendedInfo() { return "Perf stats:\n--------------------------------------------------\n" + output; } } static class PerfResultAggregator implements Aggregator<PerfResult> { @Override public PerfResult aggregate(Collection<PerfResult> results) { long cycles = 0; long instructions = 0; String output = ""; for (PerfResult r : results) { cycles += r.cycles; instructions += r.instructions; output += r.output; } return new PerfResult(output, cycles, instructions); } } }
9,639
34.836431
158
java
jmh
jmh-master/jmh-core/src/main/java/org/openjdk/jmh/profile/MemPoolProfiler.java
/* * Copyright (c) 2005, 2023, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package org.openjdk.jmh.profile; import org.openjdk.jmh.infra.BenchmarkParams; import org.openjdk.jmh.infra.IterationParams; import org.openjdk.jmh.results.*; import java.lang.management.MemoryPoolMXBean; import java.lang.management.ManagementFactory; import java.util.ArrayList; import java.util.Collection; import java.util.List; public class MemPoolProfiler implements InternalProfiler { static final double BYTES_PER_KIB = 1024D; @Override public String getDescription() { return "Memory pool/footprint profiling via standard MBeans"; } @Override public void beforeIteration(BenchmarkParams benchmarkParams, IterationParams iterationParams) { for (MemoryPoolMXBean b : ManagementFactory.getMemoryPoolMXBeans()) { b.resetPeakUsage(); } } @Override public Collection<? extends Result> afterIteration(BenchmarkParams benchmarkParams, IterationParams iterationParams, IterationResult result) { List<Result> results = new ArrayList<>(); long sumCodeHeap = 0L; long sum = 0L; for (MemoryPoolMXBean bean : ManagementFactory.getMemoryPoolMXBeans()) { long used = bean.getPeakUsage().getUsed(); if (bean.getName().contains("CodeHeap") || bean.getName().contains("Code Cache")) { sumCodeHeap += used; } sum += used; results.add(new ScalarResult(Defaults.PREFIX + "mempool." + bean.getName() + ".used", used / BYTES_PER_KIB, "KiB", AggregationPolicy.MAX)); } results.add(new ScalarResult(Defaults.PREFIX + "mempool.total.codeheap.used", sumCodeHeap / BYTES_PER_KIB, "KiB", AggregationPolicy.MAX)); results.add(new ScalarResult(Defaults.PREFIX + "mempool.total.used", sum / BYTES_PER_KIB, "KiB", AggregationPolicy.MAX)); return results; } }
3,071
41.082192
151
java
jmh
jmh-master/jmh-core/src/main/java/org/openjdk/jmh/profile/PausesProfiler.java
/* * Copyright (c) 2016, 2020, Red Hat Inc. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package org.openjdk.jmh.profile; import joptsimple.OptionException; import joptsimple.OptionParser; import joptsimple.OptionSet; import joptsimple.OptionSpec; import org.openjdk.jmh.infra.BenchmarkParams; import org.openjdk.jmh.infra.IterationParams; import org.openjdk.jmh.results.*; import org.openjdk.jmh.runner.options.IntegerValueConverter; import org.openjdk.jmh.util.SampleBuffer; import org.openjdk.jmh.util.Statistics; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.concurrent.TimeUnit; import java.util.concurrent.locks.LockSupport; public class PausesProfiler implements InternalProfiler { private Ticker ticker; private SampleBuffer buffer; private long expectedNs; private long thresh; @Override public String getDescription() { return "Pauses profiler"; } public PausesProfiler(String initLine) throws ProfilerException { OptionParser parser = new OptionParser(); parser.formatHelpWith(new ProfilerOptionFormatter(PausesProfiler.class.getCanonicalName())); OptionSpec<Integer> optSamplePeriod = parser.accepts("period", "Sampling period, in us. " + "Smaller values improve accuracy, at the expense of more profiling overhead.") .withRequiredArg().withValuesConvertedBy(IntegerValueConverter.POSITIVE).describedAs("int").defaultsTo(50); OptionSpec<Integer> optThreshold = parser.accepts("threshold", "Threshold to filter pauses, in us. " + "If unset, the threshold is figured during the initial calibration.") .withRequiredArg().withValuesConvertedBy(IntegerValueConverter.POSITIVE).describedAs("int").defaultsTo(-1); OptionSet set = ProfilerUtils.parseInitLine(initLine, parser); try { expectedNs = TimeUnit.MICROSECONDS.toNanos(set.valueOf(optSamplePeriod)); if (set.valueOf(optThreshold) != -1) { thresh = TimeUnit.MICROSECONDS.toNanos(set.valueOf(optThreshold)); } else { thresh = calibrate(); } } catch (OptionException e) { throw new ProfilerException(e.getMessage()); } } @Override public void beforeIteration(BenchmarkParams benchmarkParams, IterationParams iterationParams) { buffer = new SampleBuffer(); ticker = new Ticker(buffer); ticker.start(); } @Override public Collection<? extends Result> afterIteration(BenchmarkParams benchmarkParams, IterationParams iterationParams, IterationResult result) { ticker.interrupt(); try { ticker.join(); } catch (InterruptedException e) { // do nothing, proceed } return Collections.singletonList(new PausesProfilerResult(buffer)); } private long calibrate() { SampleBuffer buf = new SampleBuffer(); int cnt = 0; long startTime = System.nanoTime(); long lastTime = startTime; long limit = TimeUnit.SECONDS.toNanos(3); while ((cnt++ < 10_000) && (lastTime - startTime < limit)) { LockSupport.parkNanos(expectedNs); long time = System.nanoTime(); long actualNs = time - lastTime; long delta = actualNs - expectedNs; if (delta > 0) { buf.add(delta); } lastTime = time; } // The max observed pause during calibration must be our measurement // threshold. We cannot reliably guess the pauses lower than this are // caused by the benchmark pressure. Statistics stat = buf.getStatistics(1); return (long) stat.getMax(); } private class Ticker extends Thread { private final SampleBuffer buffer; public Ticker(SampleBuffer buffer) { this.buffer = buffer; setPriority(Thread.MAX_PRIORITY); setDaemon(true); } @Override public void run() { long lastTime = System.nanoTime(); while (!Thread.interrupted()) { LockSupport.parkNanos(expectedNs); long time = System.nanoTime(); long actualNs = time - lastTime; long delta = actualNs - expectedNs; if (delta > thresh) { // assume the actual pause starts within the sleep interval, // we can adjust the measurement by a half the expected time buffer.add(delta + expectedNs/2); } lastTime = time; } } } static class PausesProfilerResult extends Result<PausesProfilerResult> { private static final long serialVersionUID = 3806848321463539969L; private final SampleBuffer buffer; public PausesProfilerResult(SampleBuffer buffer) { super(ResultRole.SECONDARY, Defaults.PREFIX + "pauses", buffer.getStatistics(1D / 1_000_000), "ms", AggregationPolicy.SUM); this.buffer = buffer; } @Override protected Aggregator<PausesProfilerResult> getThreadAggregator() { return new JoiningAggregator(); } @Override protected Aggregator<PausesProfilerResult> getIterationAggregator() { return new JoiningAggregator(); } @Override protected Collection<? extends Result> getDerivativeResults() { return Arrays.asList( new ScalarDerivativeResult(Defaults.PREFIX + "pauses.avg", statistics.getMean(), "ms", AggregationPolicy.AVG), new ScalarDerivativeResult(Defaults.PREFIX + "pauses.count", statistics.getN(), "#", AggregationPolicy.SUM), new ScalarDerivativeResult(Defaults.PREFIX + "pauses.p0.00", statistics.getMin(), "ms", AggregationPolicy.MIN), new ScalarDerivativeResult(Defaults.PREFIX + "pauses.p0.50", statistics.getPercentile(50), "ms", AggregationPolicy.AVG), new ScalarDerivativeResult(Defaults.PREFIX + "pauses.p0.90", statistics.getPercentile(90), "ms", AggregationPolicy.AVG), new ScalarDerivativeResult(Defaults.PREFIX + "pauses.p0.95", statistics.getPercentile(95), "ms", AggregationPolicy.AVG), new ScalarDerivativeResult(Defaults.PREFIX + "pauses.p0.99", statistics.getPercentile(99), "ms", AggregationPolicy.AVG), new ScalarDerivativeResult(Defaults.PREFIX + "pauses.p0.999", statistics.getPercentile(99.9), "ms", AggregationPolicy.AVG), new ScalarDerivativeResult(Defaults.PREFIX + "pauses.p0.9999", statistics.getPercentile(99.99),"ms", AggregationPolicy.AVG), new ScalarDerivativeResult(Defaults.PREFIX + "pauses.p1.00", statistics.getMax(), "ms", AggregationPolicy.MAX) ); } /** * Always add up all the samples into final result. * This will allow aggregate result to achieve better accuracy. */ private static class JoiningAggregator implements Aggregator<PausesProfilerResult> { @Override public PausesProfilerResult aggregate(Collection<PausesProfilerResult> results) { SampleBuffer buffer = new SampleBuffer(); for (PausesProfilerResult r : results) { buffer.addAll(r.buffer); } return new PausesProfilerResult(buffer); } } } }
8,770
40.766667
146
java
jmh
jmh-master/jmh-core/src/main/java/org/openjdk/jmh/profile/PerfSupport.java
/* * Copyright (c) 2016, Red Hat Inc. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package org.openjdk.jmh.profile; import java.util.Collection; class PerfSupport { static final String PERF_EXEC; static { String perf = System.getenv("JMH_PERF"); PERF_EXEC = (perf == null) ? "perf" : perf; } public static boolean containsUnsupported(Collection<String> msgs, String event) { for (String m : msgs) { if (m.contains(event) && m.contains("<not supported>")) { return true; } } return false; } }
1,684
34.104167
86
java
jmh
jmh-master/jmh-core/src/main/java/org/openjdk/jmh/profile/Profiler.java
/* * Copyright (c) 2005, 2013, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package org.openjdk.jmh.profile; /** * Root profiler interface. * * <p>Profiler classes are expected to provide either a non-arg constructor, * or a constructor accepting single String argument, as the option line. * The treatment of option line is unspecified, and can be handled in * profiler-specific way. Profiler constructors can throw * {@link org.openjdk.jmh.profile.ProfilerException} if profiler cannot * operate, either because of misconfiguration, or help message requested. * The message in {@link org.openjdk.jmh.profile.ProfilerException} should * clearly articulate the reason. * * <p>JMH will try to discover profiler implementations using the SPI mechanism. * Note: discoverable implementations <em>must</em> provide a no-arg constructor * for initial discovery; the instance created during discovery will be rejected. * If implementation would have a constructor accepting the String option line, * it would be preferred for subsequent instantiation over the no-arg constructor. * * <p>Profilers normally implement one of the subinterfaces.</p> * @see org.openjdk.jmh.profile.ExternalProfiler * @see org.openjdk.jmh.profile.InternalProfiler */ public interface Profiler { /** * Human-readable one-line description of the profiler. * @return description */ String getDescription(); }
2,561
43.172414
82
java
jmh
jmh-master/jmh-core/src/main/java/org/openjdk/jmh/profile/ProfilerException.java
/* * Copyright (c) 2014, 2020, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package org.openjdk.jmh.profile; public class ProfilerException extends Exception { private static final long serialVersionUID = 1095296690895652155L; public ProfilerException(Exception e) { super(e); } public ProfilerException(String s) { super(s); } public ProfilerException(String s, Throwable e) { super(s, e); } }
1,590
35.159091
79
java
jmh
jmh-master/jmh-core/src/main/java/org/openjdk/jmh/profile/ProfilerFactory.java
/* * Copyright (c) 2005, 2013, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package org.openjdk.jmh.profile; import org.openjdk.jmh.runner.options.ProfilerConfig; import java.io.PrintStream; import java.lang.reflect.InvocationTargetException; import java.util.*; public class ProfilerFactory { public static Profiler getProfilerOrException(ProfilerConfig cfg) throws ProfilerException { try { return getProfiler(cfg); } catch (InvocationTargetException e) { if (e.getCause() instanceof ProfilerException) { throw (ProfilerException) e.getCause(); } throw new ProfilerException(e); } catch (ProfilerException e) { throw e; } catch (Exception e) { throw new ProfilerException(e); } } private static Profiler getProfilerOrNull(ProfilerConfig cfg) { try { return getProfiler(cfg); } catch (Exception e) { return null; } } private static Profiler getProfiler(ProfilerConfig cfg) throws Exception { String desc = cfg.getKlass(); // Try built-in profilers first Class<? extends Profiler> builtIn = BUILT_IN.get(desc); if (builtIn != null) { return instantiate(cfg, builtIn); } // Try discovered profilers then Collection<Class<? extends Profiler>> profilers = getDiscoveredProfilers(); for (Class<? extends Profiler> p : profilers) { if (p.getCanonicalName().equals(desc)) { return instantiate(cfg, p); } } // Try the direct hit Class<? extends Profiler> klass = (Class<? extends Profiler>) Class.forName(desc); return instantiate(cfg, klass); } private static Profiler instantiate(ProfilerConfig cfg, Class<? extends Profiler> p) throws InstantiationException, IllegalAccessException, InvocationTargetException { try { return p.getConstructor(String.class).newInstance(cfg.getOpts()); } catch (NoSuchMethodException e) { // fallthrough } try { return p.getConstructor().newInstance(); } catch (NoSuchMethodException e) { // fallthrough } throw new IllegalStateException("Cannot instantiate profiler"); } public static List<ExternalProfiler> getSupportedExternal(Collection<ProfilerConfig> cfg) { List<ExternalProfiler> profilers = new ArrayList<>(); for (ProfilerConfig p : cfg) { Profiler prof = ProfilerFactory.getProfilerOrNull(p); if (prof instanceof ExternalProfiler) { profilers.add((ExternalProfiler) prof); } } return profilers; } public static List<InternalProfiler> getSupportedInternal(Collection<ProfilerConfig> cfg) { List<InternalProfiler> profilers = new ArrayList<>(); for (ProfilerConfig p : cfg) { Profiler prof = ProfilerFactory.getProfilerOrNull(p); if (prof instanceof InternalProfiler) { profilers.add((InternalProfiler) prof); } } return profilers; } public static void listProfilers(PrintStream out) { int maxLen = 0; for (String s : BUILT_IN.keySet()) { maxLen = Math.max(maxLen, s.length()); } for (Class<? extends Profiler> s : ProfilerFactory.getDiscoveredProfilers()) { maxLen = Math.max(maxLen, s.getCanonicalName().length()); } maxLen += 2; StringBuilder supported = new StringBuilder(); StringBuilder unsupported = new StringBuilder(); for (String s : BUILT_IN.keySet()) { try { Profiler prof = getProfilerOrException(new ProfilerConfig(s, "")); supported.append(String.format("%" + maxLen + "s: %s %s\n", s, prof.getDescription(), "")); } catch (ProfilerException e) { unsupported.append(String.format("%" + maxLen + "s: %s %s\n", s, "<none>", "")); unsupported.append(e.getMessage()); unsupported.append("\n"); } } for (Class<? extends Profiler> s : ProfilerFactory.getDiscoveredProfilers()) { try { Profiler prof = getProfilerOrException(new ProfilerConfig(s.getCanonicalName(), "")); supported.append(String.format("%" + maxLen + "s: %s %s\n", s.getCanonicalName(), prof.getDescription(), "(discovered)")); } catch (ProfilerException e) { unsupported.append(String.format("%" + maxLen + "s: %s %s\n", s, s.getCanonicalName(), "")); unsupported.append(e.getMessage()); unsupported.append("\n"); } } if (!supported.toString().isEmpty()) { out.println("Supported profilers:\n" + supported.toString()); } if (!unsupported.toString().isEmpty()) { out.println("Unsupported profilers:\n" + unsupported.toString()); } } private static final Map<String, Class<? extends Profiler>> BUILT_IN; static { BUILT_IN = new TreeMap<>(); BUILT_IN.put("async", AsyncProfiler.class); BUILT_IN.put("cl", ClassloaderProfiler.class); BUILT_IN.put("comp", CompilerProfiler.class); BUILT_IN.put("gc", GCProfiler.class); BUILT_IN.put("jfr", JavaFlightRecorderProfiler.class); BUILT_IN.put("stack", StackProfiler.class); BUILT_IN.put("perf", LinuxPerfProfiler.class); BUILT_IN.put("perfnorm", LinuxPerfNormProfiler.class); BUILT_IN.put("perfasm", LinuxPerfAsmProfiler.class); BUILT_IN.put("mempool", MemPoolProfiler.class); BUILT_IN.put("xperfasm", WinPerfAsmProfiler.class); BUILT_IN.put("dtraceasm", DTraceAsmProfiler.class); BUILT_IN.put("pauses", PausesProfiler.class); BUILT_IN.put("safepoints", SafepointsProfiler.class); BUILT_IN.put("perfc2c", LinuxPerfC2CProfiler.class); } private static List<Class<? extends Profiler>> getDiscoveredProfilers() { List<Class<? extends Profiler>> profs = new ArrayList<>(); for (Profiler s : ServiceLoader.load(Profiler.class)) { profs.add(s.getClass()); } return profs; } }
7,569
38.222798
171
java
jmh
jmh-master/jmh-core/src/main/java/org/openjdk/jmh/profile/ProfilerOptionFormatter.java
/* * Copyright (c) 2005, 2014, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package org.openjdk.jmh.profile; import joptsimple.HelpFormatter; import joptsimple.OptionDescriptor; import org.openjdk.jmh.util.Utils; import java.util.List; import java.util.Map; class ProfilerOptionFormatter implements HelpFormatter { private static final String LINE_SEPARATOR = System.getProperty("line.separator"); private final String name; public ProfilerOptionFormatter(String name) { this.name = name; } public String format(Map<String, ? extends OptionDescriptor> options) { StringBuilder sb = new StringBuilder(); sb.append("Usage: -prof <profiler-name>:opt1=value1,value2;opt2=value3"); sb.append(LINE_SEPARATOR); sb.append(LINE_SEPARATOR); sb.append("Options accepted by ").append(name).append(":"); for (OptionDescriptor each : options.values()) { sb.append(lineFor(each)); } return sb.toString(); } private String lineFor(OptionDescriptor d) { StringBuilder line = new StringBuilder(); StringBuilder o = new StringBuilder(); o.append(" "); for (String str : d.options()) { if (d.representsNonOptions()) continue; o.append(str); if (d.acceptsArguments()) { o.append("="); if (d.requiresArgument()) { o.append("<"); } else { o.append("["); } o.append(d.argumentDescription()); if (d.requiresArgument()) { o.append(">"); } else { o.append("]"); } } } final int optWidth = 35; line.append(String.format("%-" + optWidth + "s", o.toString())); boolean first = true; String desc = d.description(); List<?> defaults = d.defaultValues(); if (defaults != null && !defaults.isEmpty()) { desc += " (default: " + defaults.toString() + ")"; } for (String l : Utils.rewrap(desc)) { if (first) { first = false; } else { line.append(LINE_SEPARATOR); line.append(String.format("%-" + optWidth + "s", "")); } line.append(l); } line.append(LINE_SEPARATOR); line.append(LINE_SEPARATOR); return line.toString(); } }
3,655
33.490566
86
java
jmh
jmh-master/jmh-core/src/main/java/org/openjdk/jmh/profile/ProfilerUtils.java
/* * Copyright (c) 2014, 2015, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package org.openjdk.jmh.profile; import joptsimple.OptionException; import joptsimple.OptionParser; import joptsimple.OptionSet; import joptsimple.OptionSpec; import org.openjdk.jmh.infra.IterationParams; import org.openjdk.jmh.results.BenchmarkResult; import org.openjdk.jmh.results.BenchmarkResultMetaData; import java.io.IOException; import java.io.StringWriter; import java.util.concurrent.TimeUnit; class ProfilerUtils { public static OptionSet parseInitLine(String initLine, OptionParser parser) throws ProfilerException { parser.accepts("help", "Display help."); OptionSpec<String> nonOptions = parser.nonOptions(); String[] split = initLine.split(";"); for (int c = 0; c < split.length; c++) { if (!split[c].isEmpty()) { split[c] = "-" + split[c]; } } OptionSet set; try { set = parser.parse(split); } catch (OptionException e) { try { StringWriter sw = new StringWriter(); sw.append(e.getMessage()); sw.append("\n"); parser.printHelpOn(sw); throw new ProfilerException(sw.toString()); } catch (IOException e1) { throw new ProfilerException(e1); } } if (set.has("help")) { try { StringWriter sw = new StringWriter(); parser.printHelpOn(sw); throw new ProfilerException(sw.toString()); } catch (IOException e) { e.printStackTrace(); } } String s = set.valueOf(nonOptions); if (s != null && !s.isEmpty()) { throw new ProfilerException("Unhandled options: " + s + " in " + initLine); } return set; } public static long measurementDelayMs(BenchmarkResult br) { BenchmarkResultMetaData md = br.getMetadata(); if (md != null) { // try to ask harness itself: return md.getMeasurementTime() - md.getStartTime(); } else { // metadata is not available, let's make a guess: IterationParams wp = br.getParams().getWarmup(); return wp.getCount() * wp.getTime().convertTo(TimeUnit.MILLISECONDS) + TimeUnit.SECONDS.toMillis(1); // loosely account for the JVM lag } } public static long measuredTimeMs(BenchmarkResult br) { BenchmarkResultMetaData md = br.getMetadata(); if (md != null) { // try to ask harness itself: return md.getStopTime() - md.getMeasurementTime(); } else { // metadata is not available, let's make a guess: IterationParams mp = br.getParams().getMeasurement(); return mp.getCount() * mp.getTime().convertTo(TimeUnit.MILLISECONDS); } } }
4,119
36.454545
106
java
jmh
jmh-master/jmh-core/src/main/java/org/openjdk/jmh/profile/SafepointsProfiler.java
/* * Copyright (c) 2016, 2020, Red Hat Inc. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package org.openjdk.jmh.profile; import org.openjdk.jmh.infra.BenchmarkParams; import org.openjdk.jmh.results.*; import org.openjdk.jmh.util.SampleBuffer; import java.io.BufferedReader; import java.io.File; import java.io.IOException; import java.nio.charset.Charset; import java.nio.file.Files; import java.util.*; import java.util.concurrent.TimeUnit; import java.util.regex.Matcher; import java.util.regex.Pattern; public class SafepointsProfiler implements ExternalProfiler { private static final long NO_LONG_VALUE = Long.MIN_VALUE; @Override public String getDescription() { return "Safepoints profiler"; } @Override public Collection<String> addJVMInvokeOptions(BenchmarkParams params) { return Collections.emptyList(); } @Override public Collection<String> addJVMOptions(BenchmarkParams params) { return Arrays.asList( // make sure old JVMs don't barf on Unified Logging "-XX:+IgnoreUnrecognizedVMOptions", // JDK 9+: preferred, Unified Logging "-Xlog:safepoint=info", // pre JDK-9: special options "-XX:+PrintGCApplicationStoppedTime", "-XX:+PrintGCTimeStamps" ); } @Override public void beforeTrial(BenchmarkParams benchmarkParams) { // do nothing } @Override public Collection<? extends Result> afterTrial(BenchmarkResult br, long pid, File stdOut, File stdErr) { long measuredTimeMs = ProfilerUtils.measuredTimeMs(br); long measuredTimeNs = TimeUnit.MILLISECONDS.toNanos(measuredTimeMs); long measureFrom = TimeUnit.MILLISECONDS.toNanos(ProfilerUtils.measurementDelayMs(br)); long measureTo = measureFrom + measuredTimeNs; List<ParsedData> ds = new ArrayList<>(); try (BufferedReader reader = Files.newBufferedReader(stdOut.toPath(), Charset.defaultCharset())) { String line; while ((line = reader.readLine()) != null) { ParsedData data = parse(line); if (data != null) { ds.add(data); } } } catch (IOException e) { throw new IllegalStateException(e); } // Only accept the lines from the highest version. long maxVer = Long.MIN_VALUE; for (ParsedData d : ds) { maxVer = Math.max(maxVer, d.ver); } SampleBuffer pauseBuff = new SampleBuffer(); SampleBuffer ttspBuff = new SampleBuffer(); for (ParsedData d : ds) { if (d.ver == maxVer && (d.timestamp > measureFrom) && (d.timestamp < measureTo)) { pauseBuff.add(d.stopTime); if (d.ttspTime != NO_LONG_VALUE) { ttspBuff.add(d.ttspTime); } } } Collection<Result> results = new ArrayList<>(); results.add(new ScalarResult(Defaults.PREFIX + "safepoints.interval", measuredTimeMs, "ms", AggregationPolicy.SUM)); results.add(new SafepointProfilerResult("pause", pauseBuff)); // JDK 7 does not have TTSP measurements, ignore the zero metric: if (maxVer > 7) { results.add(new SafepointProfilerResult("ttsp", ttspBuff)); } return results; } static long parseNs(String str) { return (long) (Double.parseDouble(str.replace(',', '.'))); } static long parseSecToNs(String str) { return (long) (Double.parseDouble(str.replace(',', '.')) * TimeUnit.SECONDS.toNanos(1)); } @Override public boolean allowPrintOut() { return false; } @Override public boolean allowPrintErr() { return true; } static class SafepointProfilerResult extends Result<SafepointProfilerResult> { private static final long serialVersionUID = -88756998141554941L; private final String suffix; private final SampleBuffer buffer; public SafepointProfilerResult(String suffix, SampleBuffer buffer) { super(ResultRole.SECONDARY, Defaults.PREFIX + "safepoints." + suffix, buffer.getStatistics(1D / 1_000_000), "ms", AggregationPolicy.SUM); this.suffix = suffix; this.buffer = buffer; } @Override protected Aggregator<SafepointProfilerResult> getThreadAggregator() { return new JoiningAggregator(); } @Override protected Aggregator<SafepointProfilerResult> getIterationAggregator() { return new JoiningAggregator(); } @Override protected Collection<? extends Result> getDerivativeResults() { return Arrays.asList( new ScalarDerivativeResult(Defaults.PREFIX + "safepoints." + suffix + ".avg", statistics.getMean(), "ms", AggregationPolicy.AVG), new ScalarDerivativeResult(Defaults.PREFIX + "safepoints." + suffix + ".count", statistics.getN(), "#", AggregationPolicy.SUM), new ScalarDerivativeResult(Defaults.PREFIX + "safepoints." + suffix + ".p0.00", statistics.getMin(), "ms", AggregationPolicy.MIN), new ScalarDerivativeResult(Defaults.PREFIX + "safepoints." + suffix + ".p0.50", statistics.getPercentile(50), "ms", AggregationPolicy.AVG), new ScalarDerivativeResult(Defaults.PREFIX + "safepoints." + suffix + ".p0.90", statistics.getPercentile(90), "ms", AggregationPolicy.AVG), new ScalarDerivativeResult(Defaults.PREFIX + "safepoints." + suffix + ".p0.95", statistics.getPercentile(95), "ms", AggregationPolicy.AVG), new ScalarDerivativeResult(Defaults.PREFIX + "safepoints." + suffix + ".p0.99", statistics.getPercentile(99), "ms", AggregationPolicy.AVG), new ScalarDerivativeResult(Defaults.PREFIX + "safepoints." + suffix + ".p0.999", statistics.getPercentile(99.9), "ms", AggregationPolicy.AVG), new ScalarDerivativeResult(Defaults.PREFIX + "safepoints." + suffix + ".p0.9999", statistics.getPercentile(99.99),"ms", AggregationPolicy.AVG), new ScalarDerivativeResult(Defaults.PREFIX + "safepoints." + suffix + ".p1.00", statistics.getMax(), "ms", AggregationPolicy.MAX) ); } /** * Always add up all the samples into final result. * This will allow aggregate result to achieve better accuracy. */ private static class JoiningAggregator implements Aggregator<SafepointProfilerResult> { @Override public SafepointProfilerResult aggregate(Collection<SafepointProfilerResult> results) { SampleBuffer buffer = new SampleBuffer(); String suffix = null; for (SafepointProfilerResult r : results) { buffer.addAll(r.buffer); if (suffix == null) { suffix = r.suffix; } else if (!suffix.equals(r.suffix)) { throw new IllegalStateException("Trying to aggregate results with different suffixes"); } } return new SafepointProfilerResult(suffix, buffer); } } } private static final Pattern JDK_7_LINE = Pattern.compile("([0-9\\.,]*): (.*) stopped: ([0-9\\.,]*) seconds"); private static final Pattern JDK_8_LINE = Pattern.compile("([0-9\\.,]*): (.*) stopped: ([0-9\\.,]*) seconds, (.*) took: ([0-9\\.,]*) seconds"); private static final Pattern JDK_9_LINE = Pattern.compile("\\[([0-9\\.,]*)s\\]\\[info\\]\\[safepoint( *)\\] (.*) stopped: ([0-9\\.,]*) seconds, (.*) took: ([0-9\\.,]*) seconds"); private static final Pattern JDK_13_LINE = Pattern.compile("\\[([0-9\\.,]*)s\\]\\[info\\]\\[safepoint( *)\\] (.*) Reaching safepoint: ([0-9\\.,]*) ns, (.*) Total: ([0-9\\.,]*) ns"); /** * Parse the line into the triplet. This is tested with unit tests, make sure to * update those if changing this code. */ static ParsedData parse(String line) { { Matcher m = JDK_7_LINE.matcher(line); if (m.matches()) { return new ParsedData( 7, parseSecToNs(m.group(1)), parseSecToNs(m.group(3)), NO_LONG_VALUE ); } } { Matcher m = JDK_8_LINE.matcher(line); if (m.matches()) { return new ParsedData( 8, parseSecToNs(m.group(1)), parseSecToNs(m.group(3)), parseSecToNs(m.group(5)) ); } } { Matcher m = JDK_9_LINE.matcher(line); if (m.matches()) { return new ParsedData( 9, parseSecToNs(m.group(1)), parseSecToNs(m.group(4)), parseSecToNs(m.group(6)) ); } } { Matcher m = JDK_13_LINE.matcher(line); if (m.matches()) { return new ParsedData( 13, parseSecToNs(m.group(1)), parseNs(m.group(6)), parseNs(m.group(4)) ); } } return null; } static class ParsedData { int ver; long timestamp; long stopTime; long ttspTime; public ParsedData(int ver, long timestamp, long stopTime, long ttspTime) { this.ver = ver; this.timestamp = timestamp; this.stopTime = stopTime; this.ttspTime = ttspTime; } } }
11,205
37.245734
160
java
jmh
jmh-master/jmh-core/src/main/java/org/openjdk/jmh/profile/StackProfiler.java
/* * Copyright (c) 2005, 2013, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package org.openjdk.jmh.profile; import joptsimple.OptionException; import joptsimple.OptionParser; import joptsimple.OptionSet; import joptsimple.OptionSpec; import org.openjdk.jmh.infra.BenchmarkParams; import org.openjdk.jmh.infra.IterationParams; import org.openjdk.jmh.results.*; import org.openjdk.jmh.runner.options.IntegerValueConverter; import org.openjdk.jmh.util.HashMultiset; import org.openjdk.jmh.util.Multiset; import org.openjdk.jmh.util.Multisets; import java.io.Serializable; import java.lang.management.ManagementFactory; import java.lang.management.ThreadInfo; import java.util.*; import java.util.concurrent.TimeUnit; /** * Very basic and naive stack profiler. */ public class StackProfiler implements InternalProfiler { /** * Threads to ignore (known system and harness threads) */ private static final String[] IGNORED_THREADS = { "Finalizer", "Signal Dispatcher", "Reference Handler", "main", "Sampling Thread", "Attach Listener" }; private final int stackLines; private final int topStacks; private final int periodMsec; private final boolean sampleLine; private final Set<String> excludePackageNames; public StackProfiler(String initLine) throws ProfilerException { OptionParser parser = new OptionParser(); parser.formatHelpWith(new ProfilerOptionFormatter(StackProfiler.class.getCanonicalName())); OptionSpec<Integer> optStackLines = parser.accepts("lines", "Number of stack lines to save in each stack trace. " + "Larger values provide more insight into who is calling the top stack method, as the expense " + "of more stack trace shapes to collect.") .withRequiredArg().withValuesConvertedBy(IntegerValueConverter.POSITIVE).describedAs("int").defaultsTo(1); OptionSpec<Integer> optTopStacks = parser.accepts("top", "Number of top stacks to show in the profiling results. " + "Larger values may catch some stack traces that linger in the distribution tail.") .withRequiredArg().withValuesConvertedBy(IntegerValueConverter.POSITIVE).describedAs("int").defaultsTo(10); OptionSpec<Integer> optSamplePeriod = parser.accepts("period", "Sampling period, in milliseconds. " + "Smaller values improve accuracy, at the expense of more profiling overhead.") .withRequiredArg().withValuesConvertedBy(IntegerValueConverter.POSITIVE).describedAs("int").defaultsTo(10); OptionSpec<Boolean> optDetailLine = parser.accepts("detailLine", "Record detailed source line info. " + "This adds the line numbers to the recorded stack traces.") .withRequiredArg().ofType(Boolean.class).describedAs("bool").defaultsTo(false); OptionSpec<Boolean> optExclude = parser.accepts("excludePackages", "Enable package filtering. " + "Use excludePackages option to control what packages are filtered") .withRequiredArg().ofType(Boolean.class).describedAs("bool").defaultsTo(false); OptionSpec<String> optExcludeClasses = parser.accepts("excludePackageNames", "Filter there packages. " + "This is expected to be a comma-separated list\n" + "of the fully qualified package names to be excluded. Every stack line that starts with the provided\n" + "patterns will be excluded.") .withRequiredArg().withValuesSeparatedBy(",").ofType(String.class).describedAs("package+") .defaultsTo("java.", "javax.", "sun.", "sunw.", "com.sun.", "org.openjdk.jmh."); OptionSet set = ProfilerUtils.parseInitLine(initLine, parser); try { sampleLine = set.valueOf(optDetailLine); periodMsec = set.valueOf(optSamplePeriod); topStacks = set.valueOf(optTopStacks); stackLines = set.valueOf(optStackLines); boolean excludePackages = set.valueOf(optExclude); excludePackageNames = excludePackages ? new HashSet<>(set.valuesOf(optExcludeClasses)) : Collections.<String>emptySet(); } catch (OptionException e) { throw new ProfilerException(e.getMessage()); } } private volatile SamplingTask samplingTask; @Override public void beforeIteration(BenchmarkParams benchmarkParams, IterationParams iterationParams) { samplingTask = new SamplingTask(); samplingTask.start(); } @Override public Collection<? extends Result> afterIteration(BenchmarkParams benchmarkParams, IterationParams iterationParams, IterationResult result) { samplingTask.stop(); return Collections.singleton(new StackResult(samplingTask.stacks, topStacks)); } @Override public String getDescription() { return "Simple and naive Java stack profiler"; } public class SamplingTask implements Runnable { private final Thread thread; private final Map<Thread.State, Multiset<StackRecord>> stacks; public SamplingTask() { stacks = new EnumMap<>(Thread.State.class); for (Thread.State s : Thread.State.values()) { stacks.put(s, new HashMultiset<>()); } thread = new Thread(this); thread.setName("Sampling Thread"); } @Override public void run() { while (!Thread.interrupted()) { ThreadInfo[] infos = ManagementFactory.getThreadMXBean().dumpAllThreads(false, false); info: for (ThreadInfo info : infos) { // filter out ignored threads for (String ignore : IGNORED_THREADS) { if (info.getThreadName().equalsIgnoreCase(ignore)) { continue info; } } // - Discard everything that matches excluded patterns from the top of the stack // - Get the remaining number of stack lines and build the stack record StackTraceElement[] stack = info.getStackTrace(); List<String> lines = new ArrayList<>(); for (StackTraceElement l : stack) { String className = l.getClassName(); if (!isExcluded(className)) { lines.add(className + '.' + l.getMethodName() + (sampleLine ? ":" + l.getLineNumber() : "")); if (lines.size() >= stackLines) { break; } } } if (lines.isEmpty()) { lines.add("<stack is empty, everything is filtered?>"); } Thread.State state = info.getThreadState(); stacks.get(state).add(new StackRecord(lines)); } try { TimeUnit.MILLISECONDS.sleep(periodMsec); } catch (InterruptedException e) { return; } } } public void start() { thread.start(); } public void stop() { thread.interrupt(); try { thread.join(); } catch (InterruptedException e) { Thread.currentThread().interrupt(); } } private boolean isExcluded(String className) { for (String p : excludePackageNames) { if (className.startsWith(p)) { return true; } } return false; } } private static class StackRecord implements Serializable { private static final long serialVersionUID = -1829626661894754733L; public final List<String> lines; private StackRecord(List<String> lines) { this.lines = lines; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; StackRecord that = (StackRecord) o; return lines.equals(that.lines); } @Override public int hashCode() { return lines.hashCode(); } } public static class StackResult extends Result<StackResult> { private static final long serialVersionUID = 2609170863630346073L; private final Map<Thread.State, Multiset<StackRecord>> stacks; private final int topStacks; public StackResult(Map<Thread.State, Multiset<StackRecord>> stacks, int topStacks) { super(ResultRole.SECONDARY, Defaults.PREFIX + "stack", of(Double.NaN), "---", AggregationPolicy.AVG); this.stacks = stacks; this.topStacks = topStacks; } @Override protected Aggregator<StackResult> getThreadAggregator() { return new StackResultAggregator(); } @Override protected Aggregator<StackResult> getIterationAggregator() { return new StackResultAggregator(); } @Override public String toString() { return "<delayed till summary>"; } @Override public String extendedInfo() { return getStack(stacks); } public String getStack(final Map<Thread.State, Multiset<StackRecord>> stacks) { List<Thread.State> sortedStates = new ArrayList<>(stacks.keySet()); sortedStates.sort(new Comparator<Thread.State>() { private long stateSize(Thread.State state) { Multiset<StackRecord> set = stacks.get(state); return (set == null) ? 0 : set.size(); } @Override public int compare(Thread.State s1, Thread.State s2) { return Long.compare(stateSize(s2), stateSize(s1)); } }); long totalSize = getTotalSize(stacks); StringBuilder builder = new StringBuilder(); builder.append("Stack profiler:\n\n"); builder.append(dottedLine("Thread state distributions")); for (Thread.State state : sortedStates) { if (isSignificant(stacks.get(state).size(), totalSize)) { builder.append(String.format("%5.1f%% %7s %s%n", stacks.get(state).size() * 100.0 / totalSize, "", state)); } } builder.append("\n"); for (Thread.State state : sortedStates) { Multiset<StackRecord> stateStacks = stacks.get(state); if (isSignificant(stateStacks.size(), totalSize)) { builder.append(dottedLine("Thread state: " + state.toString())); int totalDisplayed = 0; for (StackRecord s : Multisets.countHighest(stateStacks, topStacks)) { List<String> lines = s.lines; if (!lines.isEmpty()) { totalDisplayed += stateStacks.count(s); builder.append(String.format("%5.1f%% %5.1f%% %s%n", stateStacks.count(s) * 100.0 / totalSize, stateStacks.count(s) * 100.0 / stateStacks.size(), lines.get(0))); if (lines.size() > 1) { for (int i = 1; i < lines.size(); i++) { builder.append(String.format("%13s %s%n", "", lines.get(i))); } builder.append("\n"); } } } if (isSignificant((stateStacks.size() - totalDisplayed), stateStacks.size())) { builder.append(String.format("%5.1f%% %5.1f%% %s%n", (stateStacks.size() - totalDisplayed) * 100.0 / totalSize, (stateStacks.size() - totalDisplayed) * 100.0 / stateStacks.size(), "<other>")); } builder.append("\n"); } } return builder.toString(); } // returns true, if part is >0.1% of total private boolean isSignificant(long part, long total) { // returns true if part*100.0/total is greater or equals to 0.1 return part * 1000 >= total; } private long getTotalSize(Map<Thread.State, Multiset<StackRecord>> stacks) { long sum = 0; for (Multiset<StackRecord> set : stacks.values()) { sum += set.size(); } return sum; } } static String dottedLine(String header) { final int HEADER_WIDTH = 100; StringBuilder sb = new StringBuilder(); sb.append("...."); if (header != null) { header = "[" + header + "]"; sb.append(header); } else { header = ""; } for (int c = 0; c < HEADER_WIDTH - 4 - header.length(); c++) { sb.append("."); } sb.append("\n"); return sb.toString(); } public static class StackResultAggregator implements Aggregator<StackResult> { @Override public StackResult aggregate(Collection<StackResult> results) { int topStacks = 0; Map<Thread.State, Multiset<StackRecord>> sum = new EnumMap<>(Thread.State.class); for (StackResult r : results) { for (Map.Entry<Thread.State, Multiset<StackRecord>> entry : r.stacks.entrySet()) { if (!sum.containsKey(entry.getKey())) { sum.put(entry.getKey(), new HashMultiset<>()); } Multiset<StackRecord> sumSet = sum.get(entry.getKey()); for (StackRecord rec : entry.getValue().keys()) { sumSet.add(rec, entry.getValue().count(rec)); } } topStacks = r.topStacks; } return new StackResult(sum, topStacks); } } }
15,789
38.475
146
java
jmh
jmh-master/jmh-core/src/main/java/org/openjdk/jmh/profile/WinPerfAsmProfiler.java
/* * Copyright (c) 2014, 2014, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package org.openjdk.jmh.profile; import joptsimple.OptionException; import joptsimple.OptionParser; import joptsimple.OptionSpec; import org.openjdk.jmh.infra.BenchmarkParams; import org.openjdk.jmh.results.BenchmarkResult; import org.openjdk.jmh.results.Result; import org.openjdk.jmh.util.*; import java.io.*; import java.util.*; /** * Windows performance profiler based on "xperf" utility. * <p> * You must install {@code Windows Performance Toolkit}. Once installed, locate directory with {@code xperf.exe} * file and either add it to {@code PATH} environment variable, or assign it to {@code xperf.dir} parameter. * <p> * This profiler counts only {@code SampledProfile} events. To achieve this, we set {@code xperf} providers to * {@code loader+proc_thread+profile}. You may optionally save {@code xperf} binary or parsed outputs using * {@code savePerfBin} or {@code savePerf} parameters respectively. If you do so and * want to log more events, you can use {@code xperf.providers} parameter to override providers. * However, you must specify {@code loader}, {@code proc_thread} and {@code profile} providers anyway. Otherwise * sample events will not be generated and profiler will show nothing. * <p> * By default JDK distributive do not have debug symbols. If you want to analyze JVM internals, you must build OpenJDK * on your own. Once built, go to {@code bin/server} directory and unpack {@code jvm.diz}. Now you have {@code jvm.pdb} * file with JVM debug symbols. Finally, you must assign debug symbols directory to {@code symbol.dir} parameter. * <p> * This profiler behaves differently comparing to it's Linux counterpart {@link LinuxPerfAsmProfiler}. Linux profiler * employs {@code perf} utility which can be used to profile a single process. Therefore, Linux profiler wraps forked * JVM command line. In contrast, {@code xperf} cannot profile only a single process. It have {@code -PidNewProcess} * argument, but it's sole purpose is to start profiling before the process is started, so that one can be sure that * none events generated by this process are missed. It does not filter events from other processes anyhow. For this * reason, this profiler doesn't alter forked JVM startup command. Instead, it starts {@code xperf} recording in * {@link #beforeTrial(BenchmarkParams)} method, and stops in {@link ExternalProfiler#afterTrial(org.openjdk.jmh.results.BenchmarkResult, long, java.io.File, java.io.File)}. This * leaves possibility to run this profiler in conjunction with some other profiler requiring startup command * alteration. * <p> * For this reason the profiler must know PID of forked JVM process. */ public class WinPerfAsmProfiler extends AbstractPerfAsmProfiler { private static final String MSG_UNABLE_START = "Unable to start the profiler. Try running JMH as Administrator, " + "and ensure that previous profiling session is stopped. Use 'xperf -stop' to stop the active profiling session."; private static final String MSG_UNABLE_STOP = "Unable to stop the profiler. Please try running JMH as Administrator."; private final String xperfProviders; private final String symbolDir; private final String path; /** PID. */ private volatile String pid; private OptionSpec<String> optXperfDir; private OptionSpec<String> optXperfProviders; private OptionSpec<String> optSymbolDir; public WinPerfAsmProfiler(String initLine) throws ProfilerException { super(initLine, "SampledProfile"); try { String xperfDir = set.valueOf(optXperfDir); xperfProviders = set.valueOf(optXperfProviders); symbolDir = set.valueOf(optSymbolDir); path = xperfDir != null && !xperfDir.isEmpty() ? xperfDir + File.separatorChar + "xperf" : "xperf"; } catch (OptionException e) { throw new ProfilerException(e.getMessage()); } Collection<String> errsOn = Utils.tryWith(path, "-on", xperfProviders); if (!errsOn.isEmpty()) { throw new ProfilerException(MSG_UNABLE_START + ": " + errsOn); } Collection<String> errsStop = Utils.tryWith(path, "-stop"); if (!errsStop.isEmpty()) { throw new ProfilerException(MSG_UNABLE_STOP + ": " + errsStop); } } @Override protected void addMyOptions(OptionParser parser) { optXperfDir = parser.accepts("xperf.dir", "Path to \"xperf\" installation directory. Empty by default, so that xperf is expected to be in PATH.") .withRequiredArg().ofType(String.class).describedAs("path"); optXperfProviders = parser.accepts("xperf.providers", "xperf providers to use.") .withRequiredArg().ofType(String.class).describedAs("string").defaultsTo("loader+proc_thread+profile"); optSymbolDir = parser.accepts("symbol.dir", "Path to a directory with jvm.dll symbols (optional).") .withRequiredArg().ofType(String.class).describedAs("string"); } @Override public Collection<String> addJVMInvokeOptions(BenchmarkParams params) { // "xperf" cannot be started to track particular process as "perf" in Linux does. // Therefore we do not alter JVM invoke options anyhow. Instead, profiler will be started // during "before-trial" stage. return Collections.emptyList(); } @Override public void beforeTrial(BenchmarkParams params) { // Start profiler before forked JVM is started. Collection<String> errs = Utils.tryWith(path, "-on", xperfProviders); if (!errs.isEmpty()) { throw new IllegalStateException(MSG_UNABLE_START + ": " + errs); } } @Override public Collection<? extends Result> afterTrial(BenchmarkResult br, long pid, File stdOut, File stdErr) { if (pid == 0) { throw new IllegalStateException("perfasm needs the forked VM PID, but it is not initialized."); } this.pid = String.valueOf(pid); return super.afterTrial(br, pid, stdOut, stdErr); } @Override public String getDescription() { return "Windows xperf + PrintAssembly Profiler"; } @Override protected void parseEvents() { // 1. Stop profiling by calling xperf dumper. Collection<String> errs = Utils.tryWith(path, "-d", perfBinData.getAbsolutePath()); if (!errs.isEmpty()) { throw new IllegalStateException(MSG_UNABLE_STOP + ": " + errs); } // 2. Convert binary data to text form. try { ProcessBuilder pb = new ProcessBuilder(path, "-i", perfBinData.getAbsolutePath(), "-symbols", "-a", "dumper"); if (symbolDir != null) { pb.environment().put("_NT_SYMBOL_PATH", symbolDir); } Process p = pb.start(); FileOutputStream fos = new FileOutputStream(perfParsedData.file()); InputStreamDrainer errDrainer = new InputStreamDrainer(p.getErrorStream(), fos); InputStreamDrainer outDrainer = new InputStreamDrainer(p.getInputStream(), fos); errDrainer.start(); outDrainer.start(); p.waitFor(); errDrainer.join(); outDrainer.join(); } catch (IOException | InterruptedException ex) { throw new IllegalStateException(ex); } } @Override protected PerfEvents readEvents(double skipMs, double lenMs) { double readFrom = skipMs / 1000D; double readTo = (skipMs + lenMs) / 1000D; try (FileReader fr = new FileReader(perfParsedData.file()); BufferedReader reader = new BufferedReader(fr)) { Deduplicator<MethodDesc> dedup = new Deduplicator<>(); Multimap<MethodDesc, Long> methods = new HashMultimap<>(); Map<String, Multiset<Long>> events = new LinkedHashMap<>(); for (String evName : requestedEventNames) { events.put(evName, new TreeMultiset<>()); } String line; while ((line = reader.readLine()) != null) { line = line.trim(); String[] elems = line.split(",\\s+"); String evName = elems[0].trim(); // We work with only one event type - "SampledProfile". if (!requestedEventNames.get(0).equals(evName)) continue; // Check PID. String pidStr = elems[2].trim(); int pidOpenIdx = pidStr.indexOf("("); int pidCloseIdx = pidStr.indexOf(")"); if (pidOpenIdx == -1 || pidCloseIdx == -1 || pidCloseIdx < pidOpenIdx) continue; // Malformed PID, probably this is the header. pidStr = pidStr.substring(pidOpenIdx + 1, pidCloseIdx).trim(); if (!pid.equals(pidStr)) continue; // Check timestamp String timeStr = elems[1].trim(); double time = Double.parseDouble(timeStr) / 1_000_000; if (time < readFrom) continue; if (time > readTo) continue; // Get address. String addrStr = elems[4].trim().replace("0x", ""); // Get lib and function name. String libSymStr = elems[7].trim(); String lib = libSymStr.substring(0, libSymStr.indexOf('!')); String symbol = libSymStr.substring(libSymStr.indexOf('!') + 1); Multiset<Long> evs = events.get(evName); assert evs != null; try { Long addr = Long.parseLong(addrStr, 16); evs.add(addr); methods.put(dedup.dedup(MethodDesc.nativeMethod(symbol, lib)), addr); } catch (NumberFormatException e) { // kernel addresses like "ffffffff810c1b00" overflow signed long, // record them as dummy address evs.add(0L); } } IntervalMap<MethodDesc> methodMap = new IntervalMap<>(); for (MethodDesc md : methods.keys()) { Collection<Long> longs = methods.get(md); methodMap.add(md, Utils.min(longs), Utils.max(longs)); } return new PerfEvents(requestedEventNames, events, methodMap); } catch (IOException e) { throw new RuntimeException(e); } } @Override protected String perfBinaryExtension() { // Files with ".etl" extension can be opened by "Windows Performance Analyzer" right away. return ".etl"; } }
12,034
42.136201
178
java
jmh
jmh-master/jmh-core/src/main/java/org/openjdk/jmh/results/AggregationPolicy.java
/* * Copyright (c) 2014, 2014, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package org.openjdk.jmh.results; public enum AggregationPolicy { AVG("Average"), SUM("Sum"), MAX("Maximum"), MIN("Minimum"), ; private final String label; AggregationPolicy(String label) { this.label = label; } public String toString() { return label; } }
1,535
29.72
79
java
jmh
jmh-master/jmh-core/src/main/java/org/openjdk/jmh/results/Aggregator.java
/* * Copyright (c) 2005, 2013, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package org.openjdk.jmh.results; import java.util.Collection; /** * Aggregator composes multiple results into one. * * It is assumed the collection has the results of specified type. * This class is generic to save some of the unchecked casts in the code. * * @param <R> accepted result type */ public interface Aggregator<R extends Result> { /** * Aggregate the results. * @param results results to aggregate * @return aggregated result; may throw exceptions on validation errors */ R aggregate(Collection<R> results); }
1,773
37.565217
79
java
jmh
jmh-master/jmh-core/src/main/java/org/openjdk/jmh/results/AggregatorUtils.java
/* * Copyright (c) 2014, 2014, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package org.openjdk.jmh.results; import java.util.Collection; public final class AggregatorUtils { private AggregatorUtils() { // prevent instantation } static ResultRole aggregateRoles(Collection<? extends Result> results) { ResultRole result = null; for (Result r : results) { if (result == null) { result = r.role; } else if (result != r.role) { throw new IllegalStateException("Combining the results with different roles"); } } return result; } static String aggregateUnits(Collection<? extends Result> results) { String result = null; for (Result r : results) { if (result == null) { result = r.unit; } else if (!result.equals(r.unit)) { throw new IllegalStateException("Combining the results with different units"); } } return result; } static String aggregateLabels(Collection<? extends Result> results) { String result = null; for (Result r : results) { if (result == null) { result = r.label; } else if (!result.equals(r.label)) { throw new IllegalStateException("Combining the results with different labels"); } } return result; } static AggregationPolicy aggregatePolicies(Collection<? extends Result> results) { AggregationPolicy result = null; for (Result r : results) { if (result == null) { result = r.policy; } else if (!result.equals(r.policy)) { throw new IllegalStateException("Combining the results with different aggregation policies"); } } return result; } }
3,050
35.321429
109
java
jmh
jmh-master/jmh-core/src/main/java/org/openjdk/jmh/results/AverageTimeResult.java
/* * Copyright (c) 2005, 2013, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package org.openjdk.jmh.results; import org.openjdk.jmh.runner.options.TimeValue; import org.openjdk.jmh.util.ListStatistics; import org.openjdk.jmh.util.Statistics; import java.util.Collection; import java.util.concurrent.TimeUnit; /** * Result class that stores average operation time. */ public class AverageTimeResult extends Result<AverageTimeResult> { private static final long serialVersionUID = 6937689337229703312L; public AverageTimeResult(ResultRole mode, String label, double operations, long durationNs, TimeUnit tu) { this(mode, label, of(durationNs / (operations * TimeUnit.NANOSECONDS.convert(1, tu))), TimeValue.tuToString(tu) + "/op"); } AverageTimeResult(ResultRole mode, String label, Statistics value, String unit) { super(mode, label, value, unit, AggregationPolicy.AVG); } @Override protected Aggregator<AverageTimeResult> getThreadAggregator() { return new ResultAggregator(); } @Override protected Aggregator<AverageTimeResult> getIterationAggregator() { return new ResultAggregator(); } static class ResultAggregator implements Aggregator<AverageTimeResult> { @Override public AverageTimeResult aggregate(Collection<AverageTimeResult> results) { ListStatistics stat = new ListStatistics(); for (AverageTimeResult r : results) { stat.addValue(r.getScore()); } return new AverageTimeResult( AggregatorUtils.aggregateRoles(results), AggregatorUtils.aggregateLabels(results), stat, AggregatorUtils.aggregateUnits(results) ); } } }
2,973
37.623377
110
java
jmh
jmh-master/jmh-core/src/main/java/org/openjdk/jmh/results/BenchmarkResult.java
/* * Copyright (c) 2005, 2013, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package org.openjdk.jmh.results; import org.openjdk.jmh.infra.BenchmarkParams; import org.openjdk.jmh.util.HashMultimap; import org.openjdk.jmh.util.Multimap; import java.io.Serializable; import java.util.*; /** * Benchmark result. * Contains iteration results. */ public class BenchmarkResult implements Serializable { private static final long serialVersionUID = 6467912427356048369L; private final Collection<IterationResult> iterationResults; private final Multimap<String, Result> benchmarkResults; private final BenchmarkParams params; private final BenchmarkResultMetaData metadata; public BenchmarkResult(BenchmarkParams params, Collection<IterationResult> data) { this(params, data, null); } public BenchmarkResult(BenchmarkParams params, Collection<IterationResult> data, BenchmarkResultMetaData md) { this.metadata = md; this.benchmarkResults = new HashMultimap<>(); this.iterationResults = data; this.params = params; } /** * @return returns the benchmark metadata, "null" otherwise */ public BenchmarkResultMetaData getMetadata() { return metadata; } public void addBenchmarkResult(Result r) { benchmarkResults.put(r.getLabel(), r); } public Collection<IterationResult> getIterationResults() { return iterationResults; } public Multimap<String, Result> getBenchmarkResults() { return benchmarkResults; } public Result getPrimaryResult() { Aggregator<Result> aggregator = null; Collection<Result> aggrs = new ArrayList<>(); for (IterationResult r : iterationResults) { Result e = r.getPrimaryResult(); aggrs.add(e); aggregator = e.getIterationAggregator(); } for (Result r : benchmarkResults.values()) { if (r.getRole().isPrimary()) { aggrs.add(r); } } if (aggregator != null) { return aggregator.aggregate(aggrs); } else { throw new IllegalStateException("No aggregator for primary result"); } } public Map<String, Result> getSecondaryResults() { // label -> collection of results Multimap<String, Result> allSecondary = new HashMultimap<>(); // Build multiset of all results to capture if some labels are missing in some of the iterations for (IterationResult ir : iterationResults) { Map<String, Result> secondaryResults = ir.getSecondaryResults(); for (Map.Entry<String, Result> entry : secondaryResults.entrySet()) { // skip derivatives from aggregation here if (entry.getValue().getRole().isDerivative()) continue; allSecondary.put(entry.getKey(), entry.getValue()); } } Map<String, Result> answers = new TreeMap<>(); int totalIterations = iterationResults.size(); // Create "0" entries in case certain labels did not appear in some of the iterations for (String label : allSecondary.keys()) { Collection<Result> results = allSecondary.get(label); Result firstResult = results.iterator().next(); Result emptyResult = firstResult.getZeroResult(); if (emptyResult != null) { for (int i = results.size(); i < totalIterations; i++) { allSecondary.put(label, emptyResult); } } @SuppressWarnings("unchecked") Aggregator<Result> aggregator = firstResult.getIterationAggregator(); if (aggregator == null) { if (results.size() == 1) { answers.put(label, firstResult); continue; } throw new IllegalStateException("No aggregator for " + firstResult); } // Note: should not use "results" here since the contents was just updated by "put" above Result aggregate = aggregator.aggregate(allSecondary.get(label)); answers.put(label, aggregate); } for (String label : benchmarkResults.keys()) { Aggregator<Result> aggregator = null; Collection<Result> results = new ArrayList<>(); for (Result r : benchmarkResults.get(label)) { if (r.getRole().isSecondary() && !r.getRole().isDerivative()) { results.add(r); aggregator = r.getIterationAggregator(); } } if (aggregator != null) { answers.put(label, aggregator.aggregate(results)); } } // put all secondary derivative results on top: from primaries answers.putAll(produceDerivative(getPrimaryResult())); // add all derivative results on top: from secondaries Map<String, Result> adds = new HashMap<>(); for (Result r : answers.values()) { adds.putAll(produceDerivative(r)); } answers.putAll(adds); return answers; } private Map<String, Result> produceDerivative(Result r) { Map<String, Result> map = new HashMap<>(); for (Object rr : r.getDerivativeResults()) { map.put(((Result) rr).getLabel(), (Result) rr); } return map; } public String getScoreUnit() { return getPrimaryResult().getScoreUnit(); } public BenchmarkParams getParams() { return params; } }
6,774
35.820652
114
java
jmh
jmh-master/jmh-core/src/main/java/org/openjdk/jmh/results/BenchmarkResultMetaData.java
/* * Copyright (c) 2014, 2020, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package org.openjdk.jmh.results; import java.io.Serializable; public class BenchmarkResultMetaData implements Serializable { private static final long serialVersionUID = -2512961914593247551L; private long startTime; private final long warmupTime; private final long measurementTime; private final long stopTime; private final long warmupOps; private final long measurementOps; public BenchmarkResultMetaData(long warmupTime, long measurementTime, long stopTime, long warmupOps, long measurementOps) { this.startTime = Long.MIN_VALUE; this.warmupTime = warmupTime; this.measurementTime = measurementTime; this.stopTime = stopTime; this.warmupOps = warmupOps; this.measurementOps = measurementOps; } public long getStartTime() { if (startTime == Long.MIN_VALUE) { throw new IllegalStateException("Unset start time"); } return startTime; } public long getWarmupTime() { return warmupTime; } public long getMeasurementTime() { return measurementTime; } public long getStopTime() { return stopTime; } public long getMeasurementOps() { return measurementOps; } public long getWarmupOps() { return warmupOps; } public void adjustStart(long startTime) { this.startTime = startTime; } }
2,628
31.8625
127
java
jmh
jmh-master/jmh-core/src/main/java/org/openjdk/jmh/results/BenchmarkTaskResult.java
/* * Copyright (c) 2014, 2015, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package org.openjdk.jmh.results; import java.util.ArrayList; import java.util.Collection; public class BenchmarkTaskResult { /** * Total benchmark ops done. */ private final long allOperations; /** * Measured benchmark ops done: total without sync iterations. */ private final long measuredOperations; private final Collection<Result> results; public BenchmarkTaskResult(long allOperations, long measuredOperations) { this.allOperations = allOperations; this.measuredOperations = measuredOperations; this.results = new ArrayList<>(); } public void add(Result result) { results.add(result); } public Collection<Result> getResults() { return results; } public long getAllOps() { return allOperations; } public long getMeasuredOps() { return measuredOperations; } }
2,122
31.166667
79
java
jmh
jmh-master/jmh-core/src/main/java/org/openjdk/jmh/results/Defaults.java
/* * Copyright (c) 2014, 2015, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package org.openjdk.jmh.results; public class Defaults { public static final String PREFIX = "\u00b7"; }
1,325
40.4375
79
java
jmh
jmh-master/jmh-core/src/main/java/org/openjdk/jmh/results/IterationResult.java
/* * Copyright (c) 2005, 2013, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package org.openjdk.jmh.results; import org.openjdk.jmh.infra.BenchmarkParams; import org.openjdk.jmh.infra.IterationParams; import org.openjdk.jmh.util.Multimap; import org.openjdk.jmh.util.TreeMultimap; import java.io.Serializable; import java.util.*; /** * Class contains all info returned by benchmark iteration or/and collected during benchmark iteration. */ public class IterationResult implements Serializable { private static final long serialVersionUID = 960397066774710819L; private static final Multimap<String, Result> EMPTY_MAP = new TreeMultimap<>(); private static final List<Result> EMPTY_LIST = Collections.emptyList(); private final BenchmarkParams benchmarkParams; private final IterationParams params; private final IterationResultMetaData metadata; private Collection<Result> primaryResults; private Multimap<String, Result> secondaryResults; public IterationResult(BenchmarkParams benchmarkParams, IterationParams params, IterationResultMetaData md) { this.benchmarkParams = benchmarkParams; this.params = params; this.metadata = md; this.primaryResults = EMPTY_LIST; this.secondaryResults = EMPTY_MAP; } public IterationResultMetaData getMetadata() { return metadata; } public void addResults(Collection<? extends Result> rs) { for (Result r : rs) { addResult(r); } } public void addResult(Result result) { if (result.getRole().isPrimary()) { if (primaryResults == EMPTY_LIST) { primaryResults = Collections.singleton(result); } else if (primaryResults.size() == 1) { List<Result> newResults = new ArrayList<>(2); newResults.addAll(primaryResults); newResults.add(result); primaryResults = newResults; } else { primaryResults.add(result); } } if (result.getRole().isSecondary()) { if (secondaryResults == EMPTY_MAP) { secondaryResults = new TreeMultimap<>(); } secondaryResults.put(result.getLabel(), result); } } public Collection<Result> getRawPrimaryResults() { return primaryResults; } public Multimap<String, Result> getRawSecondaryResults() { return secondaryResults; } public Map<String, Result> getSecondaryResults() { Map<String, Result> answer = new TreeMap<>(); for (String label : secondaryResults.keys()) { Collection<Result> results = secondaryResults.get(label); Result next = results.iterator().next(); @SuppressWarnings("unchecked") Aggregator<Result> aggregator = next.getThreadAggregator(); Result result = aggregator.aggregate(results); answer.put(label, result); } // put all secondary derivative results on top: from primaries answer.putAll(produceDerivative(getPrimaryResult())); // add all secondary derivative results on top: from secondaries Map<String, Result> adds = new HashMap<>(); for (Result r : answer.values()) { adds.putAll(produceDerivative(r)); } answer.putAll(adds); return answer; } private Map<String, Result> produceDerivative(Result r) { Map<String, Result> map = new HashMap<>(); for (Object rr : r.getDerivativeResults()) { map.put(((Result) rr).getLabel(), (Result) rr); } return map; } public Result getPrimaryResult() { @SuppressWarnings("unchecked") Aggregator<Result> aggregator = primaryResults.iterator().next().getThreadAggregator(); return aggregator.aggregate(primaryResults); } public IterationParams getParams() { return params; } public BenchmarkParams getBenchmarkParams() { return benchmarkParams; } public String getScoreUnit() { return getPrimaryResult().getScoreUnit(); } }
5,310
34.172185
113
java
jmh
jmh-master/jmh-core/src/main/java/org/openjdk/jmh/results/IterationResultMetaData.java
/* * Copyright (c) 2014, 2020, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package org.openjdk.jmh.results; import java.io.Serializable; public class IterationResultMetaData implements Serializable { private static final long serialVersionUID = -8302904925038356897L; private final long allOps; private final long measuredOps; public IterationResultMetaData(long allOps, long measuredOps) { this.allOps = allOps; this.measuredOps = measuredOps; } public long getMeasuredOps() { return measuredOps; } public long getAllOps() { return allOps; } }
1,758
34.897959
79
java
jmh
jmh-master/jmh-core/src/main/java/org/openjdk/jmh/results/RawResults.java
/* * Copyright (c) 2005, 2013, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package org.openjdk.jmh.results; public class RawResults { public double allOps; public double measuredOps; public long realTime; public long startTime; public long stopTime; public long getTime() { return (realTime > 0) ? realTime : (stopTime - startTime); } }
1,515
36.9
79
java
jmh
jmh-master/jmh-core/src/main/java/org/openjdk/jmh/results/Result.java
/* * Copyright (c) 2005, 2013, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package org.openjdk.jmh.results; import org.openjdk.jmh.util.Deduplicator; import org.openjdk.jmh.util.ScoreFormatter; import org.openjdk.jmh.util.SingletonStatistics; import org.openjdk.jmh.util.Statistics; import java.io.PrintWriter; import java.io.Serializable; import java.io.StringWriter; import java.util.Collection; import java.util.Collections; /** * Base class for all types of results that can be returned by a benchmark. */ public abstract class Result<T extends Result<T>> implements Serializable { private static final long serialVersionUID = -7332879501317733312L; private static final Deduplicator<String> DEDUP = new Deduplicator<>(); protected final ResultRole role; protected final String label; protected final String unit; protected final Statistics statistics; protected final AggregationPolicy policy; public Result(ResultRole role, String label, Statistics s, String unit, AggregationPolicy policy) { this.role = role; this.label = DEDUP.dedup(label); this.unit = DEDUP.dedup(unit); this.statistics = s; this.policy = policy; } protected static Statistics of(double v) { return new SingletonStatistics(v); } /** * Return the result label. * @return result label */ public String getLabel() { return label; } /** * Return the result role. * @return result role */ public ResultRole getRole() { return role; } /** * Return the statistics holding the subresults' values. * * <p>This method returns raw samples. The aggregation policy decides how to get the score * out of these raw samples. Use {@link #getScore()}, {@link #getScoreError()}, and * {@link #getScoreConfidence()} for scalar results.</p> * * @return statistics */ public Statistics getStatistics() { return statistics; } /** * The unit of the score for this result. * * @return String representation of the unit */ public final String getScoreUnit() { return unit; } /** * The score for this result. * * @return double representing the score * @see #getScoreError() */ public double getScore() { switch (policy) { case AVG: return statistics.getMean(); case SUM: return statistics.getSum(); case MAX: return statistics.getMax(); case MIN: return statistics.getMin(); default: throw new IllegalStateException("Unknown aggregation policy: " + policy); } } /** * The score error for this result. * @return score error, if available * @see #getScore() */ public double getScoreError() { switch (policy) { case AVG: return statistics.getMeanErrorAt(0.999); case SUM: case MIN: case MAX: return Double.NaN; default: throw new IllegalStateException("Unknown aggregation policy: " + policy); } } /** * The score confidence interval for this result. * @return score confidence interval, if available; if not, the CI will match {@link #getScore()} * @see #getScore() */ public double[] getScoreConfidence() { switch (policy) { case AVG: return statistics.getConfidenceIntervalAt(0.999); case MAX: case MIN: case SUM: double score = getScore(); return new double[] {score, score}; default: throw new IllegalStateException("Unknown aggregation policy: " + policy); } } /** * Get number of samples in the current result. * @return number of samples */ public long getSampleCount() { return statistics.getN(); } /** * Thread aggregator combines the thread results into iteration result. * @return thread aggregator */ protected abstract Aggregator<T> getThreadAggregator(); /** * Iteration aggregator combines the iteration results into benchmar result. * @return iteration aggregator */ protected abstract Aggregator<T> getIterationAggregator(); /** * Returns "0" result. This is used for un-biased aggregation of secondary results. * For instance, profilers might omit results in some iterations, thus we should pretend there were 0 results. * @return result that represents "empty" result, null if no sensible "empty" result can be created */ protected T getZeroResult() { return null; } /** * @return derivative results for this result. These do not participate in aggregation, * and computed on the spot from the aggregated result. */ protected Collection<? extends Result> getDerivativeResults() { return Collections.emptyList(); } /** * Result as represented by a String. * * @return String with the result and unit */ @Override public String toString() { if (!Double.isNaN(getScoreError()) && !ScoreFormatter.isApproximate(getScore())) { return String.format("%s \u00B1(99.9%%) %s %s", ScoreFormatter.format(getScore()), ScoreFormatter.formatError(getScoreError()), getScoreUnit()); } else { return String.format("%s %s", ScoreFormatter.format(getScore()), getScoreUnit()); } } /** * Print extended result information * @return String with extended info */ public String extendedInfo() { return simpleExtendedInfo(); } protected String simpleExtendedInfo() { StringWriter sw = new StringWriter(); PrintWriter pw = new PrintWriter(sw); Statistics stats = getStatistics(); if (stats.getN() > 2 && !ScoreFormatter.isApproximate(getScore())) { double[] interval = getScoreConfidence(); pw.println(String.format(" %s \u00B1(99.9%%) %s %s [%s]", ScoreFormatter.format(getScore()), ScoreFormatter.formatError((interval[1] - interval[0]) / 2), getScoreUnit(), policy)); pw.println(String.format(" (min, avg, max) = (%s, %s, %s), stdev = %s%n" + " CI (99.9%%): [%s, %s] (assumes normal distribution)", ScoreFormatter.format(stats.getMin()), ScoreFormatter.format(stats.getMean()), ScoreFormatter.format(stats.getMax()), ScoreFormatter.formatError(stats.getStandardDeviation()), ScoreFormatter.format(interval[0]), ScoreFormatter.format(interval[1])) ); } else { pw.println(String.format(" %s %s", ScoreFormatter.format(stats.getMean()), getScoreUnit())); } pw.close(); return sw.toString(); } protected String distributionExtendedInfo() { Statistics stats = getStatistics(); StringBuilder sb = new StringBuilder(); if (stats.getN() > 2) { sb.append(" N = ").append(stats.getN()).append("\n"); double[] interval = stats.getConfidenceIntervalAt(0.999); sb.append(String.format(" mean = %s \u00B1(99.9%%) %s", ScoreFormatter.format(10, stats.getMean()), ScoreFormatter.formatError((interval[1] - interval[0]) / 2) )); sb.append(" ").append(getScoreUnit()).append("\n"); printHisto(stats, sb); printPercentiles(stats, sb); } return sb.toString(); } private void printPercentiles(Statistics stats, StringBuilder sb) { sb.append("\n Percentiles, ").append(getScoreUnit()).append(":\n"); for (double p : new double[]{0.00, 0.50, 0.90, 0.95, 0.99, 0.999, 0.9999, 0.99999, 0.999999, 1.0}) { sb.append(String.format(" %11s = %s %s\n", "p(" + String.format("%.4f", p * 100) + ")", ScoreFormatter.format(10, stats.getPercentile(p * 100)), getScoreUnit() )); } } static class LazyProps { private static final int MIN_HISTOGRAM_BINS = Integer.getInteger("jmh.histogramBins", 10); } private void printHisto(Statistics stats, StringBuilder sb) { sb.append("\n Histogram, ").append(getScoreUnit()).append(":\n"); double min = stats.getMin(); double max = stats.getMax(); double binSize = Math.pow(10, Math.floor(Math.log10(max - min))); min = Math.floor(min / binSize) * binSize; max = Math.ceil(max / binSize) * binSize; double range = max - min; double[] levels; if (range > 0) { while ((range / binSize) < LazyProps.MIN_HISTOGRAM_BINS) { binSize /= 2; } int binCount = Math.max(2, (int) Math.ceil(range / binSize)); levels = new double[binCount]; for (int c = 0; c < binCount; c++) { levels[c] = min + (c * binSize); } } else { levels = new double[] { stats.getMin() - Math.ulp(stats.getMin()), stats.getMax() + Math.ulp(stats.getMax()) }; } int width = ScoreFormatter.format(1, max).length(); int[] histo = stats.getHistogram(levels); for (int c = 0; c < levels.length - 1; c++) { sb.append(String.format(" [%" + width + "s, %" + width + "s) = %d %n", ScoreFormatter.formatExact(width, levels[c]), ScoreFormatter.formatExact(width, levels[c + 1]), histo[c])); } } }
11,269
33.255319
114
java
jmh
jmh-master/jmh-core/src/main/java/org/openjdk/jmh/results/ResultRole.java
/* * Copyright (c) 2005, 2013, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package org.openjdk.jmh.results; public enum ResultRole { /** * Participates in primary metric calculation. */ PRIMARY, /** * Participates in secondary metric calculations. */ SECONDARY, /** * Same as {@link #SECONDARY}, but always recomputed. */ SECONDARY_DERIVATIVE, /** * Does not participate in any metric, garbage result. */ OMITTED, ; public boolean isPrimary() { return this == PRIMARY; } public boolean isSecondary() { return this == SECONDARY || this == SECONDARY_DERIVATIVE; } public boolean isDerivative() { return this == SECONDARY_DERIVATIVE; } }
1,906
29.269841
79
java
jmh
jmh-master/jmh-core/src/main/java/org/openjdk/jmh/results/RunResult.java
/* * Copyright (c) 2005, 2013, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package org.openjdk.jmh.results; import org.openjdk.jmh.infra.BenchmarkParams; import java.io.Serializable; import java.util.ArrayList; import java.util.Collection; import java.util.Comparator; import java.util.Map; /** * Complete run result. * Contains the iteration results. */ public class RunResult implements Serializable { private static final long serialVersionUID = 6467912427356048369L; private final Collection<BenchmarkResult> benchmarkResults; private final BenchmarkParams params; public RunResult(BenchmarkParams params, Collection<BenchmarkResult> data) { this.benchmarkResults = data; this.params = params; } public Collection<BenchmarkResult> getBenchmarkResults() { return benchmarkResults; } public Result getPrimaryResult() { return getAggregatedResult().getPrimaryResult(); } public Map<String, Result> getSecondaryResults() { return getAggregatedResult().getSecondaryResults(); } /** * Return the benchmark result, as if all iterations from all sub-benchmark results * were merged in a single result. * * @return merged benchmark result */ public BenchmarkResult getAggregatedResult() { if (benchmarkResults.isEmpty()) { return null; } Collection<IterationResult> results = new ArrayList<>(); for (BenchmarkResult r : benchmarkResults) { results.addAll(r.getIterationResults()); } BenchmarkResult result = new BenchmarkResult(params, results); for (BenchmarkResult br : benchmarkResults) { for (String k : br.getBenchmarkResults().keys()) { for (Result r : br.getBenchmarkResults().get(k)) { result.addBenchmarkResult(r); } } } return result; } public BenchmarkParams getParams() { return params; } public static final Comparator<RunResult> DEFAULT_SORT_COMPARATOR = Comparator.comparing(o -> o.params); }
3,272
33.09375
108
java
jmh
jmh-master/jmh-core/src/main/java/org/openjdk/jmh/results/SampleTimeResult.java
/* * Copyright (c) 2005, 2013, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package org.openjdk.jmh.results; import org.openjdk.jmh.runner.options.TimeValue; import org.openjdk.jmh.util.SampleBuffer; import org.openjdk.jmh.util.Statistics; import java.util.Arrays; import java.util.Collection; import java.util.concurrent.TimeUnit; /** * Result class that samples operation time. */ public class SampleTimeResult extends Result<SampleTimeResult> { private static final long serialVersionUID = -295298353763294757L; private final SampleBuffer buffer; private final TimeUnit outputTimeUnit; public SampleTimeResult(ResultRole role, String label, SampleBuffer buffer, TimeUnit outputTimeUnit) { this(role, label, buffer, TimeValue.tuToString(outputTimeUnit) + "/op", outputTimeUnit); } SampleTimeResult(ResultRole role, String label, SampleBuffer buffer, String unit, TimeUnit outputTimeUnit) { super(role, label, of(buffer, outputTimeUnit), unit, AggregationPolicy.AVG); this.buffer = buffer; this.outputTimeUnit = outputTimeUnit; } private static Statistics of(SampleBuffer buffer, TimeUnit outputTimeUnit) { double tuMultiplier = 1.0D * outputTimeUnit.convert(1, TimeUnit.DAYS) / TimeUnit.NANOSECONDS.convert(1, TimeUnit.DAYS); return buffer.getStatistics(tuMultiplier); } @Override protected Collection<? extends Result> getDerivativeResults() { return Arrays.asList( new ScalarDerivativeResult(label + Defaults.PREFIX + "p0.00", statistics.getPercentile(0), getScoreUnit(), AggregationPolicy.AVG), new ScalarDerivativeResult(label + Defaults.PREFIX + "p0.50", statistics.getPercentile(50), getScoreUnit(), AggregationPolicy.AVG), new ScalarDerivativeResult(label + Defaults.PREFIX + "p0.90", statistics.getPercentile(90), getScoreUnit(), AggregationPolicy.AVG), new ScalarDerivativeResult(label + Defaults.PREFIX + "p0.95", statistics.getPercentile(95), getScoreUnit(), AggregationPolicy.AVG), new ScalarDerivativeResult(label + Defaults.PREFIX + "p0.99", statistics.getPercentile(99), getScoreUnit(), AggregationPolicy.AVG), new ScalarDerivativeResult(label + Defaults.PREFIX + "p0.999", statistics.getPercentile(99.9), getScoreUnit(), AggregationPolicy.AVG), new ScalarDerivativeResult(label + Defaults.PREFIX + "p0.9999", statistics.getPercentile(99.99), getScoreUnit(), AggregationPolicy.AVG), new ScalarDerivativeResult(label + Defaults.PREFIX + "p1.00", statistics.getPercentile(100), getScoreUnit(), AggregationPolicy.AVG) ); } @Override public String extendedInfo() { return distributionExtendedInfo(); } @Override protected Aggregator<SampleTimeResult> getThreadAggregator() { return new JoiningAggregator(); } @Override protected Aggregator<SampleTimeResult> getIterationAggregator() { return new JoiningAggregator(); } /** * Always add up all the samples into final result. * This will allow aggregate result to achieve better accuracy. */ static class JoiningAggregator implements Aggregator<SampleTimeResult> { @Override public SampleTimeResult aggregate(Collection<SampleTimeResult> results) { SampleBuffer buffer = new SampleBuffer(); TimeUnit tu = null; for (SampleTimeResult r : results) { buffer.addAll(r.buffer); if (tu == null) { tu = r.outputTimeUnit; } else if (!tu.equals(r.outputTimeUnit)){ throw new IllegalStateException("Combining the results with different timeunits"); } } return new SampleTimeResult( AggregatorUtils.aggregateRoles(results), AggregatorUtils.aggregateLabels(results), buffer, AggregatorUtils.aggregateUnits(results), tu ); } } }
5,410
42.637097
155
java
jmh
jmh-master/jmh-core/src/main/java/org/openjdk/jmh/results/ScalarDerivativeResult.java
/* * Copyright (c) 2014, 2014, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package org.openjdk.jmh.results; import org.openjdk.jmh.util.ListStatistics; import org.openjdk.jmh.util.Statistics; import java.util.Collection; public class ScalarDerivativeResult extends Result<ScalarDerivativeResult> { private static final long serialVersionUID = 3407232747805728586L; public ScalarDerivativeResult(String label, double n, String unit, AggregationPolicy policy) { this(label, of(n), unit, policy); } ScalarDerivativeResult(String label, Statistics s, String unit, AggregationPolicy policy) { super(ResultRole.SECONDARY_DERIVATIVE, label, s, unit, policy); } @Override protected Aggregator<ScalarDerivativeResult> getThreadAggregator() { return new ScalarResultAggregator(); } @Override protected Aggregator<ScalarDerivativeResult> getIterationAggregator() { return new ScalarResultAggregator(); } @Override protected ScalarDerivativeResult getZeroResult() { return new ScalarDerivativeResult(label, 0, unit, policy); } static class ScalarResultAggregator implements Aggregator<ScalarDerivativeResult> { @Override public ScalarDerivativeResult aggregate(Collection<ScalarDerivativeResult> results) { ListStatistics stats = new ListStatistics(); for (ScalarDerivativeResult r : results) { stats.addValue(r.getScore()); } return new ScalarDerivativeResult( AggregatorUtils.aggregateLabels(results), stats, AggregatorUtils.aggregateUnits(results), AggregatorUtils.aggregatePolicies(results) ); } } @Override public String extendedInfo() { return ""; } }
2,998
36.962025
98
java
jmh
jmh-master/jmh-core/src/main/java/org/openjdk/jmh/results/ScalarResult.java
/* * Copyright (c) 2014, 2014, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package org.openjdk.jmh.results; import org.openjdk.jmh.util.ListStatistics; import org.openjdk.jmh.util.Statistics; import java.util.Collection; public class ScalarResult extends Result<ScalarResult> { private static final long serialVersionUID = 3407232747805728586L; public ScalarResult(String label, double n, String unit, AggregationPolicy policy) { this(label, of(n), unit, policy); } ScalarResult(String label, Statistics s, String unit, AggregationPolicy policy) { super(ResultRole.SECONDARY, label, s, unit, policy); } @Override protected Aggregator<ScalarResult> getThreadAggregator() { return new ScalarResultAggregator(); } @Override protected Aggregator<ScalarResult> getIterationAggregator() { return new ScalarResultAggregator(); } @Override protected ScalarResult getZeroResult() { return new ScalarResult(label, 0, unit, policy); } static class ScalarResultAggregator implements Aggregator<ScalarResult> { @Override public ScalarResult aggregate(Collection<ScalarResult> results) { ListStatistics stats = new ListStatistics(); for (ScalarResult r : results) { stats.addValue(r.getScore()); } return new ScalarResult( AggregatorUtils.aggregateLabels(results), stats, AggregatorUtils.aggregateUnits(results), AggregatorUtils.aggregatePolicies(results) ); } } }
2,782
36.608108
88
java
jmh
jmh-master/jmh-core/src/main/java/org/openjdk/jmh/results/SingleShotResult.java
/* * Copyright (c) 2005, 2013, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package org.openjdk.jmh.results; import org.openjdk.jmh.runner.options.TimeValue; import org.openjdk.jmh.util.ListStatistics; import org.openjdk.jmh.util.Statistics; import java.util.Collection; import java.util.concurrent.TimeUnit; /** * Result class that stores once operation execution time. */ public class SingleShotResult extends Result<SingleShotResult> { private static final long serialVersionUID = -1251578870918524737L; public SingleShotResult(ResultRole role, String label, long duration, TimeUnit outputTimeUnit) { // TODO: Transition interface, should be removed when we decide it is OK to break the publicly leaked API. this(role, label, duration, 1, outputTimeUnit); } public SingleShotResult(ResultRole role, String label, long duration, long ops, TimeUnit outputTimeUnit) { this(role, label, of(1.0D * duration / ops / TimeUnit.NANOSECONDS.convert(1, outputTimeUnit)), TimeValue.tuToString(outputTimeUnit) + "/op"); } SingleShotResult(ResultRole mode, String label, Statistics s, String unit) { super(mode, label, s, unit, AggregationPolicy.AVG); } @Override public String extendedInfo() { return distributionExtendedInfo(); } @Override protected Aggregator<SingleShotResult> getThreadAggregator() { return new AveragingAggregator(); } @Override protected Aggregator<SingleShotResult> getIterationAggregator() { return new AveragingAggregator(); } /** * Averages the time on all levels. */ static class AveragingAggregator implements Aggregator<SingleShotResult> { @Override public SingleShotResult aggregate(Collection<SingleShotResult> results) { ListStatistics stat = new ListStatistics(); for (SingleShotResult r : results) { stat.addValue(r.getScore()); } return new SingleShotResult( AggregatorUtils.aggregateRoles(results), AggregatorUtils.aggregateLabels(results), stat, AggregatorUtils.aggregateUnits(results) ); } } }
3,427
36.67033
114
java
jmh
jmh-master/jmh-core/src/main/java/org/openjdk/jmh/results/TextResult.java
/* * Copyright (c) 2014, 2020, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package org.openjdk.jmh.results; public class TextResult extends Result<TextResult> { private static final long serialVersionUID = 6871141606856800453L; final String output; final String label; public TextResult(String output, String label) { super(ResultRole.SECONDARY, Defaults.PREFIX + label, of(Double.NaN), "---", AggregationPolicy.AVG); this.output = output; this.label = label; } @Override protected Aggregator<TextResult> getThreadAggregator() { return new TextResultAggregator(); } @Override protected Aggregator<TextResult> getIterationAggregator() { return new TextResultAggregator(); } @Override public String toString() { return "(text only)"; } @Override public String extendedInfo() { return output; } }
2,063
33.983051
107
java
jmh
jmh-master/jmh-core/src/main/java/org/openjdk/jmh/results/TextResultAggregator.java
/* * Copyright (c) 2014, 2020, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package org.openjdk.jmh.results; import java.util.Collection; class TextResultAggregator implements Aggregator<TextResult> { @Override public TextResult aggregate(Collection<TextResult> results) { StringBuilder output = new StringBuilder(); String label = null; for (TextResult r : results) { output.append(r.output); if (label == null) { label = r.label; } else if (!label.equalsIgnoreCase(r.label)) { throw new IllegalStateException("Trying to aggregate different labels: " + label + ", " + r.label); } } return new TextResult(output.toString(), label); } }
1,907
41.4
115
java
jmh
jmh-master/jmh-core/src/main/java/org/openjdk/jmh/results/ThroughputResult.java
/* * Copyright (c) 2005, 2013, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package org.openjdk.jmh.results; import org.openjdk.jmh.runner.options.TimeValue; import org.openjdk.jmh.util.ListStatistics; import org.openjdk.jmh.util.Statistics; import java.util.Collection; import java.util.concurrent.TimeUnit; /** * Result class that counts the number of operations performed during a specified unit of time. */ public class ThroughputResult extends Result<ThroughputResult> { private static final long serialVersionUID = 7269598073169413322L; public ThroughputResult(ResultRole role, String label, double operations, long durationNs, TimeUnit outputTimeUnit) { this(role, label, of(operations * TimeUnit.NANOSECONDS.convert(1, outputTimeUnit) / durationNs), "ops/" + TimeValue.tuToString(outputTimeUnit), AggregationPolicy.SUM); } ThroughputResult(ResultRole role, String label, Statistics s, String unit, AggregationPolicy policy) { super(role, label, s, unit, policy); } @Override protected Aggregator<ThroughputResult> getThreadAggregator() { return new ThroughputAggregator(AggregationPolicy.SUM); } @Override protected Aggregator<ThroughputResult> getIterationAggregator() { return new ThroughputAggregator(AggregationPolicy.AVG); } static class ThroughputAggregator implements Aggregator<ThroughputResult> { private final AggregationPolicy policy; ThroughputAggregator(AggregationPolicy policy) { this.policy = policy; } @Override public ThroughputResult aggregate(Collection<ThroughputResult> results) { ListStatistics stat = new ListStatistics(); for (ThroughputResult r : results) { stat.addValue(r.getScore()); } return new ThroughputResult( AggregatorUtils.aggregateRoles(results), AggregatorUtils.aggregateLabels(results), stat, AggregatorUtils.aggregateUnits(results), policy ); } } }
3,316
38.023529
121
java
jmh
jmh-master/jmh-core/src/main/java/org/openjdk/jmh/results/format/JSONResultFormat.java
/* * Copyright (c) 2005, 2013, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package org.openjdk.jmh.results.format; import org.openjdk.jmh.infra.BenchmarkParams; import org.openjdk.jmh.results.BenchmarkResult; import org.openjdk.jmh.results.IterationResult; import org.openjdk.jmh.results.Result; import org.openjdk.jmh.results.RunResult; import org.openjdk.jmh.util.Statistics; import org.openjdk.jmh.util.Utils; import java.io.PrintStream; import java.io.PrintWriter; import java.io.StringWriter; import java.util.ArrayList; import java.util.Collection; import java.util.Map; class JSONResultFormat implements ResultFormat { private static final boolean PRINT_RAW_DATA = Boolean.parseBoolean(System.getProperty("jmh.json.rawData", "true")); private final PrintStream out; public JSONResultFormat(PrintStream out) { this.out = out; } @Override public void writeOut(Collection<RunResult> results) { StringWriter sw = new StringWriter(); PrintWriter pw = new PrintWriter(sw); boolean first = true; pw.println("["); for (RunResult runResult : results) { BenchmarkParams params = runResult.getParams(); if (first) { first = false; pw.println(); } else { pw.println(","); } pw.println("{"); pw.println("\"jmhVersion\" : \"" + params.getJmhVersion() + "\","); pw.println("\"benchmark\" : \"" + params.getBenchmark() + "\","); pw.println("\"mode\" : \"" + params.getMode().shortLabel() + "\","); pw.println("\"threads\" : " + params.getThreads() + ","); pw.println("\"forks\" : " + params.getForks() + ","); pw.println("\"jvm\" : " + toJsonString(params.getJvm()) + ","); // if empty, write an empty array. pw.println("\"jvmArgs\" : ["); printStringArray(pw, params.getJvmArgs()); pw.println("],"); pw.println("\"jdkVersion\" : " + toJsonString(params.getJdkVersion()) + ","); pw.println("\"vmName\" : " + toJsonString(params.getVmName()) + ","); pw.println("\"vmVersion\" : " + toJsonString(params.getVmVersion()) + ","); pw.println("\"warmupIterations\" : " + params.getWarmup().getCount() + ","); pw.println("\"warmupTime\" : \"" + params.getWarmup().getTime() + "\","); pw.println("\"warmupBatchSize\" : " + params.getWarmup().getBatchSize() + ","); pw.println("\"measurementIterations\" : " + params.getMeasurement().getCount() + ","); pw.println("\"measurementTime\" : \"" + params.getMeasurement().getTime() + "\","); pw.println("\"measurementBatchSize\" : " + params.getMeasurement().getBatchSize() + ","); if (!params.getParamsKeys().isEmpty()) { pw.println("\"params\" : {"); pw.println(emitParams(params)); pw.println("},"); } Result primaryResult = runResult.getPrimaryResult(); pw.println("\"primaryMetric\" : {"); pw.println("\"score\" : " + emit(primaryResult.getScore()) + ","); pw.println("\"scoreError\" : " + emit(primaryResult.getScoreError()) + ","); pw.println("\"scoreConfidence\" : " + emit(primaryResult.getScoreConfidence()) + ","); pw.println(emitPercentiles(primaryResult.getStatistics())); pw.println("\"scoreUnit\" : \"" + primaryResult.getScoreUnit() + "\","); switch (params.getMode()) { case SampleTime: pw.println("\"rawDataHistogram\" :"); pw.println(getRawData(runResult, true)); break; default: pw.println("\"rawData\" :"); pw.println(getRawData(runResult, false)); } pw.println("},"); // primaryMetric end Collection<String> secondaries = new ArrayList<>(); for (Map.Entry<String, Result> e : runResult.getSecondaryResults().entrySet()) { String secondaryName = e.getKey(); Result result = e.getValue(); StringBuilder sb = new StringBuilder(); sb.append("\"").append(secondaryName).append("\" : {"); sb.append("\"score\" : ").append(emit(result.getScore())).append(","); sb.append("\"scoreError\" : ").append(emit(result.getScoreError())).append(","); sb.append("\"scoreConfidence\" : ").append(emit(result.getScoreConfidence())).append(","); sb.append(emitPercentiles(result.getStatistics())); sb.append("\"scoreUnit\" : \"").append(result.getScoreUnit()).append("\","); sb.append("\"rawData\" : "); Collection<String> l2 = new ArrayList<>(); for (BenchmarkResult benchmarkResult : runResult.getBenchmarkResults()) { Collection<String> scores = new ArrayList<>(); for (IterationResult r : benchmarkResult.getIterationResults()) { Result rr = r.getSecondaryResults().get(secondaryName); if (rr != null) { scores.add(emit(rr.getScore())); } } l2.add(printMultiple(scores, "[", "]")); } sb.append(printMultiple(l2, "[", "]")); sb.append("}"); secondaries.add(sb.toString()); } pw.println("\"secondaryMetrics\" : {"); pw.println(printMultiple(secondaries, "", "")); pw.println("}"); pw.print("}"); // benchmark end } pw.println("]"); out.println(tidy(sw.toString())); } private String getRawData(RunResult runResult, boolean histogram) { StringBuilder sb = new StringBuilder(); Collection<String> runs = new ArrayList<>(); if (PRINT_RAW_DATA) { for (BenchmarkResult benchmarkResult : runResult.getBenchmarkResults()) { Collection<String> iterations = new ArrayList<>(); for (IterationResult r : benchmarkResult.getIterationResults()) { if (histogram) { Collection<String> singleIter = new ArrayList<>(); for (Map.Entry<Double, Long> item : Utils.adaptForLoop(r.getPrimaryResult().getStatistics().getRawData())) { singleIter.add("< " + emit(item.getKey()) + "; " + item.getValue() + " >"); } iterations.add(printMultiple(singleIter, "[", "]")); } else { iterations.add(emit(r.getPrimaryResult().getScore())); } } runs.add(printMultiple(iterations, "[", "]")); } } sb.append(printMultiple(runs, "[", "]")); return sb.toString(); } private String emitParams(BenchmarkParams params) { StringBuilder sb = new StringBuilder(); boolean isFirst = true; for (String k : params.getParamsKeys()) { if (isFirst) { isFirst = false; } else { sb.append(", "); } sb.append("\"").append(k).append("\" : "); sb.append(toJsonString(params.getParam(k))); } return sb.toString(); } private String emitPercentiles(Statistics stats) { StringBuilder sb = new StringBuilder(); sb.append("\"scorePercentiles\" : {"); boolean firstPercentile = true; for (double p : new double[]{0.00, 50.0, 90, 95, 99, 99.9, 99.99, 99.999, 99.9999, 100}) { if (firstPercentile) { firstPercentile = false; } else { sb.append(","); } double v = stats.getPercentile(p); sb.append("\"").append(emit(p)).append("\" : "); sb.append(emit(v)); } sb.append("},"); return sb.toString(); } private String emit(double[] ds) { StringBuilder sb = new StringBuilder(); boolean isFirst = true; sb.append("["); for (double d : ds) { if (isFirst) { isFirst = false; } else { sb.append(","); } sb.append(emit(d)); } sb.append("]"); return sb.toString(); } private String emit(double d) { if (d != d) return "\"NaN\""; if (d == Double.NEGATIVE_INFINITY) return "\"-INF\""; if (d == Double.POSITIVE_INFINITY) return "\"+INF\""; return String.valueOf(d); } /** * Escaping for a JSON string. Does the typical escaping of double quotes and backslash. * Also escapes characters that are handled by the tidying process, so that every ASCII * character makes it correctly into the JSON output. Control characters are filtered. */ static String toJsonString(String s) { StringBuilder sb = new StringBuilder(); sb.append("\""); for (char c : s.toCharArray()) { if (Character.isISOControl(c)) { continue; } switch (c) { // use & as escape character to escape the tidying case '&': sb.append("&&"); break; // we cannot escape to \\\\ since this would create sequences interpreted by the tidying case '\\': sb.append("&/"); break; case '"': sb.append("&'"); break; // escape spacial chars for the tidying formatting below that might appear in a string case ',': sb.append(";"); break; case '[': sb.append("<"); break; case ']': sb.append(">"); break; case '<': sb.append("&-"); break; case '>': sb.append("&="); break; case ';': sb.append("&:"); break; case '{': sb.append("&("); break; case '}': sb.append("&)"); break; default: sb.append(c); } } sb.append("\""); return sb.toString(); } static String tidy(String s) { s = s.replaceAll("\r", ""); s = s.replaceAll("\n", " "); s = s.replaceAll(",", ",\n"); s = s.replaceAll("\\{", "{\n"); s = s.replaceAll("\\[", "[\n"); s = s.replaceAll("\\}", "\n}\n"); s = s.replaceAll("\\]", "\n]\n"); s = s.replaceAll("\\]\n,\n", "],\n"); s = s.replaceAll("\\}\n,\n", "},\n"); s = s.replaceAll("\n( *)\n", "\n"); // Keep these inline: s = s.replaceAll(";", ","); s = s.replaceAll("\\<", "["); s = s.replaceAll("\\>", "]"); // translate back from string escaping to keep all string characters intact s = s.replaceAll("&:", ";"); s = s.replaceAll("&'", "\\\\\""); s = s.replaceAll("&\\(", "{"); s = s.replaceAll("&\\)", "}"); s = s.replaceAll("&-", "<"); s = s.replaceAll("&=", ">"); s = s.replaceAll("&/", "\\\\\\\\"); s = s.replaceAll("&&", "&"); String[] lines = s.split("\n"); StringBuilder sb = new StringBuilder(); int ident = 0; String prevL = null; for (String l : lines) { if (prevL != null && (prevL.endsWith("{") || prevL.endsWith("["))) { ident++; } if (l.equals("}") || l.equals("]") || l.equals("},") || l.equals("],")) { ident--; } for (int c = 0; c < ident; c++) { sb.append(" "); } sb.append(l.trim()); sb.append("\n"); prevL = l; } return sb.toString(); } private String printMultiple(Collection<String> elements, String leftBracket, String rightBracket) { StringBuilder sb = new StringBuilder(); sb.append(leftBracket); boolean isFirst = true; for (String e : elements) { if (isFirst) { isFirst = false; } else { sb.append(","); } sb.append(e); } sb.append(rightBracket); return sb.toString(); } private static void printStringArray(PrintWriter pw, Collection<String> col) { boolean isFirst = true; for (String e : col) { if (isFirst) { isFirst = false; } else { pw.print(','); } pw.print(toJsonString(e)); } } }
14,019
37.944444
132
java
jmh
jmh-master/jmh-core/src/main/java/org/openjdk/jmh/results/format/LaTeXResultFormat.java
/* * Copyright (c) 2005, 2014, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package org.openjdk.jmh.results.format; import org.openjdk.jmh.infra.BenchmarkParams; import org.openjdk.jmh.results.Result; import org.openjdk.jmh.results.RunResult; import org.openjdk.jmh.util.ClassUtils; import org.openjdk.jmh.util.ScoreFormatter; import java.io.PrintStream; import java.util.Collection; import java.util.HashSet; import java.util.Map; import java.util.Set; import java.util.SortedSet; import java.util.TreeSet; class LaTeXResultFormat implements ResultFormat { private final PrintStream out; public LaTeXResultFormat(PrintStream out) { this.out = out; } @Override public void writeOut(Collection<RunResult> results) { SortedSet<String> params = new TreeSet<>(); Set<String> benchNames = new HashSet<>(); Set<String> units = new HashSet<>(); for (RunResult rr : results) { String benchmark = rr.getParams().getBenchmark(); benchNames.add(benchmark); params.addAll(rr.getParams().getParamsKeys()); units.add(rr.getPrimaryResult().getScoreUnit()); Map<String, Result> secondaries = rr.getSecondaryResults(); for (String label : secondaries.keySet()) { benchNames.add(benchmark + ":" + label); units.add(secondaries.get(label).getScoreUnit()); } } boolean singleUnit = (units.size() == 1); String unit = singleUnit ? units.iterator().next() : null; Map<String, String> prefixes = ClassUtils.denseClassNames(benchNames); printHeader(params, singleUnit, unit); for (RunResult rr : results) { BenchmarkParams bp = rr.getParams(); String benchmark = bp.getBenchmark(); Result res = rr.getPrimaryResult(); printLine(benchmark, bp, params, prefixes, singleUnit, res); Map<String, Result> secondaries = rr.getSecondaryResults(); for (String label : secondaries.keySet()) { Result subRes = secondaries.get(label); printLine(benchmark + ":" + label, bp, params, prefixes, singleUnit, subRes); } } printFooter(); } private void printHeader(SortedSet<String> params, boolean singleUnit, String unit) { out.print("\\begin{tabular}{r|"); for (String p : params) { out.print("l|"); } out.print("rl" + (singleUnit ? "" : "l") + "}\n"); out.print(" \\multicolumn{1}{c|}{\\texttt{Benchmark}} & "); for (String p : params) { out.printf("\\texttt{%s} & ", p); } out.print("\\multicolumn{" + (singleUnit ? 2 : 3) + "}{c}{\\texttt{Score" + (singleUnit ? ", " + unit : "") + "}} \\\\\n"); out.print("\\hline\n"); } private void printFooter() { out.print("\\end{tabular}"); } private void printLine(String label, BenchmarkParams benchParams, SortedSet<String> params, Map<String, String> prefixes, boolean singleUnit, Result res) { out.printf("\\texttt{%s} & ", escape(prefixes.get(label))); for (String p : params) { out.printf("\\texttt{%s} & ", escape(benchParams.getParam(p))); } out.printf("\\texttt{%s} & ", ScoreFormatter.formatLatex(res.getScore())); if (!Double.isNaN(res.getScoreError()) && !ScoreFormatter.isApproximate(res.getScore())) { out.printf("\\scriptsize $\\pm$ \\texttt{%s} ", ScoreFormatter.formatError(res.getScoreError())); } if (!singleUnit) { out.print("& "); out.printf("\\texttt{%s}", escape(res.getScoreUnit())); } out.print(" \\\\\n"); } private static String escape(String s) { return s.replaceAll("_", "\\\\_") .replaceAll("#", "\\\\#") .replaceAll("\\{", "\\\\{") .replaceAll("\\}", "\\\\}"); } }
5,157
36.926471
131
java
jmh
jmh-master/jmh-core/src/main/java/org/openjdk/jmh/results/format/ResultFormat.java
/* * Copyright (c) 2005, 2013, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package org.openjdk.jmh.results.format; import org.openjdk.jmh.results.RunResult; import java.util.Collection; public interface ResultFormat { void writeOut(Collection<RunResult> results); }
1,413
38.277778
79
java
jmh
jmh-master/jmh-core/src/main/java/org/openjdk/jmh/results/format/ResultFormatFactory.java
/* * Copyright (c) 2005, 2013, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package org.openjdk.jmh.results.format; import org.openjdk.jmh.results.RunResult; import java.io.IOException; import java.io.PrintStream; import java.util.Collection; public class ResultFormatFactory { private ResultFormatFactory() {} /** * Get the instance of ResultFormat of given type which writes the result to file * @param type result format type * @param file target file * @return result format */ public static ResultFormat getInstance(final ResultFormatType type, final String file) { return results -> { try { PrintStream pw = new PrintStream(file, "UTF-8"); ResultFormat rf = getInstance(type, pw); rf.writeOut(results); pw.flush(); pw.close(); } catch (IOException e) { throw new IllegalStateException(e); } }; } /** * Get the instance of ResultFormat of given type which write the result to out. * It is a user responsibility to initialize and finish the out as appropriate. * * @param type result format type * @param out target out * @return result format. */ public static ResultFormat getInstance(ResultFormatType type, PrintStream out) { switch (type) { case TEXT: return new TextResultFormat(out); case CSV: return new XSVResultFormat(out, ","); case SCSV: /* * Since some implementations, notably Excel, think it is a good * idea to hijack the CSV standard, and use semi-colon instead of * comma in some locales, this is the specialised * Semi-Colon Separated Values formatter. */ return new XSVResultFormat(out, ";"); case JSON: return new JSONResultFormat(out); case LATEX: return new LaTeXResultFormat(out); default: throw new IllegalStateException("Unsupported result format: " + type); } } }
3,372
36.898876
92
java
jmh
jmh-master/jmh-core/src/main/java/org/openjdk/jmh/results/format/ResultFormatType.java
/* * Copyright (c) 2005, 2013, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package org.openjdk.jmh.results.format; public enum ResultFormatType { TEXT, CSV, SCSV, JSON, LATEX, }
1,339
36.222222
79
java
jmh
jmh-master/jmh-core/src/main/java/org/openjdk/jmh/results/format/TextResultFormat.java
/* * Copyright (c) 2014, 2014, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package org.openjdk.jmh.results.format; import org.openjdk.jmh.infra.BenchmarkParams; import org.openjdk.jmh.results.Result; import org.openjdk.jmh.results.RunResult; import org.openjdk.jmh.util.ClassUtils; import org.openjdk.jmh.util.ScoreFormatter; import java.io.PrintStream; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.Map; import java.util.SortedSet; import java.util.TreeSet; class TextResultFormat implements ResultFormat { private final PrintStream out; public TextResultFormat(PrintStream out) { this.out = out; } @Override public void writeOut(Collection<RunResult> runResults) { final int COLUMN_PAD = 2; Collection<String> benchNames = new ArrayList<>(); for (RunResult runResult : runResults) { benchNames.add(runResult.getParams().getBenchmark()); for (String label : runResult.getSecondaryResults().keySet()) { benchNames.add(runResult.getParams().getBenchmark() + ":" + label); } } Map<String, String> benchPrefixes = ClassUtils.denseClassNames(benchNames); // determine name column length int nameLen = "Benchmark".length(); for (String prefix : benchPrefixes.values()) { nameLen = Math.max(nameLen, prefix.length()); } // determine param lengths Map<String, Integer> paramLengths = new HashMap<>(); SortedSet<String> params = new TreeSet<>(); for (RunResult runResult : runResults) { BenchmarkParams bp = runResult.getParams(); for (String k : bp.getParamsKeys()) { params.add(k); Integer len = paramLengths.get(k); if (len == null) { len = ("(" + k + ")").length() + COLUMN_PAD; } paramLengths.put(k, Math.max(len, bp.getParam(k).length() + COLUMN_PAD)); } } // determine column lengths for other columns int modeLen = "Mode".length(); int samplesLen = "Cnt".length(); int scoreLen = "Score".length(); int scoreErrLen = "Error".length(); int unitLen = "Units".length(); for (RunResult res : runResults) { Result primRes = res.getPrimaryResult(); modeLen = Math.max(modeLen, res.getParams().getMode().shortLabel().length()); samplesLen = Math.max(samplesLen, String.format("%d", primRes.getSampleCount()).length()); scoreLen = Math.max(scoreLen, ScoreFormatter.format(primRes.getScore()).length()); scoreErrLen = Math.max(scoreErrLen, ScoreFormatter.format(primRes.getScoreError()).length()); unitLen = Math.max(unitLen, primRes.getScoreUnit().length()); for (Result subRes : res.getSecondaryResults().values()) { samplesLen = Math.max(samplesLen, String.format("%d", subRes.getSampleCount()).length()); scoreLen = Math.max(scoreLen, ScoreFormatter.format(subRes.getScore()).length()); scoreErrLen = Math.max(scoreErrLen, ScoreFormatter.format(subRes.getScoreError()).length()); unitLen = Math.max(unitLen, subRes.getScoreUnit().length()); } } modeLen += COLUMN_PAD; samplesLen += COLUMN_PAD; scoreLen += COLUMN_PAD; scoreErrLen += COLUMN_PAD - 1; // digest a single character for +- separator unitLen += COLUMN_PAD; out.printf("%-" + nameLen + "s", "Benchmark"); for (String k : params) { out.printf("%" + paramLengths.get(k) + "s", "(" + k + ")"); } out.printf("%" + modeLen + "s", "Mode"); out.printf("%" + samplesLen + "s", "Cnt"); out.printf("%" + scoreLen + "s", "Score"); out.print(" "); out.printf("%" + scoreErrLen + "s", "Error"); out.printf("%" + unitLen + "s", "Units"); out.println(); for (RunResult res : runResults) { { out.printf("%-" + nameLen + "s", benchPrefixes.get(res.getParams().getBenchmark())); for (String k : params) { String v = res.getParams().getParam(k); out.printf("%" + paramLengths.get(k) + "s", (v == null) ? "N/A" : v); } Result pRes = res.getPrimaryResult(); out.printf("%" + modeLen + "s", res.getParams().getMode().shortLabel()); if (pRes.getSampleCount() > 1) { out.printf("%" + samplesLen + "d", pRes.getSampleCount()); } else { out.printf("%" + samplesLen + "s", ""); } out.print(ScoreFormatter.format(scoreLen, pRes.getScore())); if (!Double.isNaN(pRes.getScoreError()) && !ScoreFormatter.isApproximate(pRes.getScore())) { out.print(" \u00B1"); out.print(ScoreFormatter.formatError(scoreErrLen, pRes.getScoreError())); } else { out.print(" "); out.printf("%" + scoreErrLen + "s", ""); } out.printf("%" + unitLen + "s", pRes.getScoreUnit()); out.println(); } for (Map.Entry<String, Result> e : res.getSecondaryResults().entrySet()) { String label = e.getKey(); Result subRes = e.getValue(); out.printf("%-" + nameLen + "s", benchPrefixes.get(res.getParams().getBenchmark() + ":" + label)); for (String k : params) { String v = res.getParams().getParam(k); out.printf("%" + paramLengths.get(k) + "s", (v == null) ? "N/A" : v); } out.printf("%" + modeLen + "s", res.getParams().getMode().shortLabel()); if (subRes.getSampleCount() > 1) { out.printf("%" + samplesLen + "d", subRes.getSampleCount()); } else { out.printf("%" + samplesLen + "s", ""); } out.print(ScoreFormatter.format(scoreLen, subRes.getScore())); if (!Double.isNaN(subRes.getScoreError()) && !ScoreFormatter.isApproximate(subRes.getScore())) { out.print(" \u00B1"); out.print(ScoreFormatter.formatError(scoreErrLen, subRes.getScoreError())); } else { out.print(" "); out.printf("%" + scoreErrLen + "s", ""); } out.printf("%" + unitLen + "s", subRes.getScoreUnit()); out.println(); } } } }
8,068
40.592784
112
java
jmh
jmh-master/jmh-core/src/main/java/org/openjdk/jmh/results/format/XSVResultFormat.java
/* * Copyright (c) 2005, 2014, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package org.openjdk.jmh.results.format; import org.openjdk.jmh.infra.BenchmarkParams; import org.openjdk.jmh.results.Result; import org.openjdk.jmh.results.RunResult; import java.io.PrintStream; import java.util.Collection; import java.util.SortedSet; import java.util.TreeSet; /* * CSV formatter follows the provisions of http://tools.ietf.org/html/rfc4180 */ class XSVResultFormat implements ResultFormat { private final PrintStream out; private final String delimiter; public XSVResultFormat(PrintStream out, String delimiter) { this.out = out; this.delimiter = delimiter; } @Override public void writeOut(Collection<RunResult> results) { SortedSet<String> params = new TreeSet<>(); for (RunResult res : results) { params.addAll(res.getParams().getParamsKeys()); } printHeader(params); for (RunResult rr : results) { BenchmarkParams benchParams = rr.getParams(); Result res = rr.getPrimaryResult(); printLine(benchParams.getBenchmark(), benchParams, params, res); for (String label : rr.getSecondaryResults().keySet()) { Result subRes = rr.getSecondaryResults().get(label); printLine(benchParams.getBenchmark() + ":" + subRes.getLabel(), benchParams, params, subRes); } } } private void printHeader(SortedSet<String> params) { out.print("\"Benchmark\""); out.print(delimiter); out.print("\"Mode\""); out.print(delimiter); out.print("\"Threads\""); out.print(delimiter); out.print("\"Samples\""); out.print(delimiter); out.print("\"Score\""); out.print(delimiter); out.printf("\"Score Error (%.1f%%)\"", 99.9); out.print(delimiter); out.print("\"Unit\""); for (String k : params) { out.print(delimiter); out.print("\"Param: " + k + "\""); } out.print("\r\n"); } private void printLine(String label, BenchmarkParams benchmarkParams, SortedSet<String> params, Result result) { out.print("\""); out.print(label); out.print("\""); out.print(delimiter); out.print("\""); out.print(benchmarkParams.getMode().shortLabel()); out.print("\""); out.print(delimiter); out.print(emit(benchmarkParams.getThreads())); out.print(delimiter); out.print(emit(result.getSampleCount())); out.print(delimiter); out.print(emit(result.getScore())); out.print(delimiter); out.print(emit(result.getScoreError())); out.print(delimiter); out.print("\""); out.print(result.getScoreUnit()); out.print("\""); for (String p : params) { out.print(delimiter); String v = benchmarkParams.getParam(p); if (v != null) { out.print(emit(v)); } } out.print("\r\n"); } private String emit(String v) { if (v.contains(delimiter) || v.contains(" ") || v.contains("\n") || v.contains("\r") || v.contains("\"")) { return "\"" + v.replaceAll("\"", "\"\"") + "\""; } else { return v; } } private String emit(int i) { return emit(String.format("%d", i)); } private String emit(long l) { return emit(String.format("%d", l)); } private String emit(double d) { return emit(String.format("%f", d)); } }
4,794
32.068966
116
java
jmh
jmh-master/jmh-core/src/main/java/org/openjdk/jmh/runner/AbstractResourceReader.java
/* * Copyright (c) 2005, 2013, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package org.openjdk.jmh.runner; import java.io.*; import java.net.URL; import java.nio.charset.StandardCharsets; import java.util.ArrayList; import java.util.Collections; import java.util.Enumeration; import java.util.List; class AbstractResourceReader { private final String file; private final String resource; private final String strings; protected AbstractResourceReader(String file, String resource, String strings) { this.file = file; this.resource = resource; this.strings = strings; } /** * Helper method for creating a Reader for the list file. * * @return a correct Reader instance */ protected List<Reader> getReaders() { if (strings != null) { return Collections.<Reader>singletonList(new StringReader(strings)); } if (file != null) { try { return Collections.<Reader>singletonList(new InputStreamReader(new FileInputStream(file), StandardCharsets.UTF_8)); } catch (FileNotFoundException e) { throw new RuntimeException("ERROR: Could not find resource", e); } } if (resource != null) { Enumeration<URL> urls; try { urls = getClass().getClassLoader().getResources( resource.startsWith("/") ? resource.substring(1) : resource ); } catch (IOException e) { throw new RuntimeException("ERROR: While obtaining resource: " + resource, e); } if (urls.hasMoreElements()) { List<Reader> readers = new ArrayList<>(); URL url = null; try { while (urls.hasMoreElements()) { url = urls.nextElement(); InputStream stream = url.openStream(); readers.add(new InputStreamReader(stream, StandardCharsets.UTF_8)); } } catch (IOException e) { for (Reader r : readers) { try { r.close(); } catch (IOException e1) { // ignore } } throw new RuntimeException("ERROR: While opening resource: " + url, e); } return readers; } else { throw new RuntimeException("ERROR: Unable to find the resource: " + resource); } } throw new IllegalStateException(); } }
3,909
35.542056
131
java
jmh
jmh-master/jmh-core/src/main/java/org/openjdk/jmh/runner/Action.java
/* * Copyright (c) 2005, 2013, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package org.openjdk.jmh.runner; import org.openjdk.jmh.infra.BenchmarkParams; import java.io.Serializable; class Action implements Serializable { private static final long serialVersionUID = -7315320958163363586L; private final BenchmarkParams params; private final ActionMode mode; public Action(BenchmarkParams params, ActionMode mode) { this.params = params; this.mode = mode; } public ActionMode getMode() { return mode; } public BenchmarkParams getParams() { return params; } }
1,771
34.44
79
java
jmh
jmh-master/jmh-core/src/main/java/org/openjdk/jmh/runner/ActionMode.java
/* * Copyright (c) 2005, 2013, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package org.openjdk.jmh.runner; enum ActionMode { /** * No action. */ UNDEF(false, false), /** * Do warmup only. */ WARMUP(true, false), /** * Do measurement only. */ MEASUREMENT(false, true), /** * Do both warmup and measurement */ WARMUP_MEASUREMENT(true, true), ; private final boolean doWarmup; private final boolean doMeasurement; ActionMode(boolean doWarmup, boolean doMeasurement) { this.doWarmup = doWarmup; this.doMeasurement = doMeasurement; } public boolean doWarmup() { return doWarmup; } public boolean doMeasurement() { return doMeasurement; } }
1,922
28.136364
79
java
jmh
jmh-master/jmh-core/src/main/java/org/openjdk/jmh/runner/ActionPlan.java
/* * Copyright (c) 2005, 2013, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package org.openjdk.jmh.runner; import java.io.Serializable; import java.util.ArrayList; import java.util.List; public class ActionPlan implements Serializable { private static final long serialVersionUID = 7250784375093638099L; private final List<Action> actions; private final ActionType type; public ActionPlan(ActionType type) { this.type = type; this.actions = new ArrayList<>(); } public ActionType getType() { return type; } public void add(Action action) { actions.add(action); } public void mixIn(ActionPlan other) { actions.addAll(other.actions); } public List<Action> getActions() { return actions; } public List<Action> getMeasurementActions() { List<Action> result = new ArrayList<>(); for (Action action : actions) { switch (action.getMode()) { case MEASUREMENT: case WARMUP_MEASUREMENT: result.add(action); break; } } return result; } }
2,312
30.684932
79
java
jmh
jmh-master/jmh-core/src/main/java/org/openjdk/jmh/runner/ActionType.java
/* * Copyright (c) 2005, 2014, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package org.openjdk.jmh.runner; enum ActionType { EMBEDDED, FORKED, }
1,292
40.709677
79
java
jmh
jmh-master/jmh-core/src/main/java/org/openjdk/jmh/runner/BaseRunner.java
/* * Copyright (c) 2005, 2013, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package org.openjdk.jmh.runner; import org.openjdk.jmh.annotations.Mode; import org.openjdk.jmh.infra.BenchmarkParams; import org.openjdk.jmh.infra.IterationParams; import org.openjdk.jmh.results.BenchmarkResult; import org.openjdk.jmh.results.BenchmarkResultMetaData; import org.openjdk.jmh.results.IterationResult; import org.openjdk.jmh.runner.format.OutputFormat; import org.openjdk.jmh.runner.options.Options; import org.openjdk.jmh.util.Multimap; import org.openjdk.jmh.util.TreeMultimap; import org.openjdk.jmh.util.Utils; import java.lang.management.GarbageCollectorMXBean; import java.lang.management.ManagementFactory; import java.util.ArrayList; import java.util.Collection; import java.util.List; import java.util.concurrent.TimeUnit; /** * Abstract runner, the base class for Runner and ForkedRunner. */ abstract class BaseRunner { private long projectedTotalTime; private long projectedRunningTime; private long actualRunningTime; private long benchmarkStart; protected final Options options; protected final OutputFormat out; public BaseRunner(Options options, OutputFormat handler) { if (options == null) { throw new IllegalArgumentException("Options is null."); } if (handler == null) { throw new IllegalArgumentException("Handler is null."); } this.options = options; this.out = handler; } protected void runBenchmarksForked(ActionPlan actionPlan, IterationResultAcceptor acceptor) { for (Action action : actionPlan.getActions()) { BenchmarkParams params = action.getParams(); ActionMode mode = action.getMode(); doSingle(params, mode, acceptor); } } protected Multimap<BenchmarkParams, BenchmarkResult> runBenchmarksEmbedded(ActionPlan actionPlan) { Multimap<BenchmarkParams, BenchmarkResult> results = new TreeMultimap<>(); for (Action action : actionPlan.getActions()) { BenchmarkParams params = action.getParams(); ActionMode mode = action.getMode(); long startTime = System.currentTimeMillis(); out.startBenchmark(params); out.println(""); etaBeforeBenchmark(); out.println("# Fork: N/A, test runs in the host VM"); out.println("# *** WARNING: Non-forked runs may silently omit JVM options, mess up profilers, disable compiler hints, etc. ***"); out.println("# *** WARNING: Use non-forked runs only for debugging purposes, not for actual performance runs. ***"); final List<IterationResult> res = new ArrayList<>(); final List<BenchmarkResultMetaData> mds = new ArrayList<>(); IterationResultAcceptor acceptor = new IterationResultAcceptor() { @Override public void accept(IterationResult iterationData) { res.add(iterationData); } @Override public void acceptMeta(BenchmarkResultMetaData md) { mds.add(md); } }; doSingle(params, mode, acceptor); if (!res.isEmpty()) { BenchmarkResultMetaData md = mds.get(0); if (md != null) { md.adjustStart(startTime); } BenchmarkResult br = new BenchmarkResult(params, res, md); results.put(params, br); out.endBenchmark(br); } etaAfterBenchmark(params); } return results; } private void doSingle(BenchmarkParams params, ActionMode mode, IterationResultAcceptor acceptor) { try { switch (mode) { case WARMUP: { runBenchmark(params, null); out.println(""); break; } case WARMUP_MEASUREMENT: case MEASUREMENT: { runBenchmark(params, acceptor); break; } default: throw new IllegalStateException("Unknown mode: " + mode); } } catch (BenchmarkException be) { out.println("<failure>"); out.println(""); for (Throwable cause : be.getSuppressed()) { out.println(Utils.throwableToString(cause)); } out.println(""); if (options.shouldFailOnError().orElse(Defaults.FAIL_ON_ERROR)) { throw be; } } } protected void etaAfterBenchmark(BenchmarkParams params) { long current = System.nanoTime(); projectedRunningTime += estimateTimeSingleFork(params); actualRunningTime += (current - benchmarkStart); benchmarkStart = current; } protected void etaBeforeBenchmarks(Collection<ActionPlan> plans) { projectedTotalTime = 0; for (ActionPlan plan : plans) { for (Action act : plan.getActions()) { BenchmarkParams params = act.getParams(); projectedTotalTime += (Math.max(1, params.getForks()) + params.getWarmupForks()) * estimateTimeSingleFork(params); } } } private long estimateTimeSingleFork(BenchmarkParams params) { IterationParams wp = params.getWarmup(); IterationParams mp = params.getMeasurement(); long estimatedTime; if (params.getMode() == Mode.SingleShotTime) { // No way to tell how long it will execute, // guess anything, and let ETA compensation to catch up. estimatedTime = (wp.getCount() + mp.getCount()) * TimeUnit.MILLISECONDS.toNanos(1); } else { estimatedTime = (wp.getCount() * wp.getTime().convertTo(TimeUnit.NANOSECONDS) + mp.getCount() * mp.getTime().convertTo(TimeUnit.NANOSECONDS)); } return estimatedTime; } protected void etaBeforeBenchmark() { if (benchmarkStart == 0) { benchmarkStart = System.nanoTime(); } long totalETA; double partsDone = 1.0D * projectedRunningTime / projectedTotalTime; if (partsDone != 0) { totalETA = (long) (actualRunningTime * (1.0D / partsDone - 1)); } else { totalETA = projectedTotalTime; } out.println(String.format("# Run progress: %.2f%% complete, ETA %s", partsDone * 100, formatDuration(totalETA))); } protected void etaAfterBenchmarks() { out.println(String.format("# Run complete. Total time: %s", formatDuration(actualRunningTime))); out.println(""); } private String formatDuration(long nanos) { long days = TimeUnit.NANOSECONDS.toDays(nanos); nanos -= days * TimeUnit.DAYS.toNanos(1); long hrs = TimeUnit.NANOSECONDS.toHours(nanos); nanos -= hrs * TimeUnit.HOURS.toNanos(1); long mins = TimeUnit.NANOSECONDS.toMinutes(nanos); nanos -= mins * TimeUnit.MINUTES.toNanos(1); long secs = TimeUnit.NANOSECONDS.toSeconds(nanos); return String.format("%s%02d:%02d:%02d", (days > 0) ? days + " days, " : "", hrs, mins, secs); } void runBenchmark(BenchmarkParams benchParams, IterationResultAcceptor acceptor) { BenchmarkHandler handler = null; try { handler = new BenchmarkHandler(out, options, benchParams); runBenchmark(benchParams, handler, acceptor); } catch (BenchmarkException be) { throw be; } catch (Throwable ex) { throw new BenchmarkException(ex); } finally { if (handler != null) { handler.shutdown(); } } } protected void runBenchmark(BenchmarkParams benchParams, BenchmarkHandler handler, IterationResultAcceptor acceptor) { long warmupTime = System.currentTimeMillis(); long allWarmup = 0; long allMeasurement = 0; // warmup IterationParams wp = benchParams.getWarmup(); for (int i = 1; i <= wp.getCount(); i++) { // will run system gc if we should if (runSystemGC()) { out.verbosePrintln("System.gc() executed"); } out.iteration(benchParams, wp, i); boolean isFirstIteration = (i == 1); boolean isLastIteration = (benchParams.getMeasurement().getCount() == 0); IterationResult ir = handler.runIteration(benchParams, wp, isFirstIteration, isLastIteration); out.iterationResult(benchParams, wp, i, ir); allWarmup += ir.getMetadata().getAllOps(); } long measurementTime = System.currentTimeMillis(); // measurement IterationParams mp = benchParams.getMeasurement(); for (int i = 1; i <= mp.getCount(); i++) { // will run system gc if we should if (runSystemGC()) { out.verbosePrintln("System.gc() executed"); } // run benchmark iteration out.iteration(benchParams, mp, i); boolean isFirstIteration = (benchParams.getWarmup().getCount() == 0) && (i == 1); boolean isLastIteration = (i == mp.getCount()); IterationResult ir = handler.runIteration(benchParams, mp, isFirstIteration, isLastIteration); out.iterationResult(benchParams, mp, i, ir); allMeasurement += ir.getMetadata().getAllOps(); if (acceptor != null) { acceptor.accept(ir); } } long stopTime = System.currentTimeMillis(); BenchmarkResultMetaData md = new BenchmarkResultMetaData( warmupTime, measurementTime, stopTime, allWarmup, allMeasurement); if (acceptor != null) { acceptor.acceptMeta(md); } } /** * Execute System.gc() if we the System.gc option is set. * * @return true if we did */ public boolean runSystemGC() { if (options.shouldDoGC().orElse(Defaults.DO_GC)) { List<GarbageCollectorMXBean> enabledBeans = new ArrayList<>(); long beforeGcCount = 0; for (GarbageCollectorMXBean bean : ManagementFactory.getGarbageCollectorMXBeans()) { long count = bean.getCollectionCount(); if (count != -1) { enabledBeans.add(bean); } } for (GarbageCollectorMXBean bean : enabledBeans) { beforeGcCount += bean.getCollectionCount(); } // Run the GC twice, and force finalization before each GCs. System.runFinalization(); System.gc(); System.runFinalization(); System.gc(); // Now make sure GC actually happened. We have to wait for two things: // a) That at least two collections happened, indicating GC work. // b) That counter updates have not happened for a while, indicating GC work had ceased. // // Note there is an opportunity window for a concurrent GC to happen before the first // System.gc() call, which would get counted towards our GCs. This race is unresolvable // unless we have GC-specific information about the collection cycles, and verify those // were indeed GCs triggered by us. final int MAX_WAIT_MSEC = 20 * 1000; if (enabledBeans.isEmpty()) { out.println("WARNING: MXBeans can not report GC info. System.gc() invoked, pessimistically waiting " + MAX_WAIT_MSEC + " msecs"); try { TimeUnit.MILLISECONDS.sleep(MAX_WAIT_MSEC); } catch (InterruptedException e) { Thread.currentThread().interrupt(); } return true; } boolean gcHappened = false; long start = System.nanoTime(); while (TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - start) < MAX_WAIT_MSEC) { try { TimeUnit.MILLISECONDS.sleep(200); } catch (InterruptedException e) { Thread.currentThread().interrupt(); } long afterGcCount = 0; for (GarbageCollectorMXBean bean : enabledBeans) { afterGcCount += bean.getCollectionCount(); } if (!gcHappened) { if (afterGcCount - beforeGcCount >= 2) { gcHappened = true; } } else { if (afterGcCount == beforeGcCount) { // Stable! return true; } beforeGcCount = afterGcCount; } } if (gcHappened) { out.println("WARNING: System.gc() was invoked but unable to wait while GC stopped, is GC too asynchronous?"); } else { out.println("WARNING: System.gc() was invoked but couldn't detect a GC occurring, is System.gc() disabled?"); } return false; } return false; } }
14,619
36.391304
145
java
jmh
jmh-master/jmh-core/src/main/java/org/openjdk/jmh/runner/BenchmarkException.java
/* * Copyright (c) 2005, 2014, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package org.openjdk.jmh.runner; import java.util.Collection; import java.util.Collections; /** * Internal exception in JMH. Always wraps the real cause. */ public class BenchmarkException extends RuntimeException { private static final long serialVersionUID = 4064666042830679837L; public BenchmarkException(Throwable ex) { this("Benchmark error", Collections.singleton(ex)); } public BenchmarkException(String msg, Collection<Throwable> errors) { super(msg); for (Throwable err : errors) { if (err != null) { addSuppressed(err); } } } @Override public Throwable getCause() { return null; } }
1,925
34.666667
79
java
jmh
jmh-master/jmh-core/src/main/java/org/openjdk/jmh/runner/BenchmarkHandler.java
/* * Copyright (c) 2005, 2023, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package org.openjdk.jmh.runner; import org.openjdk.jmh.infra.BenchmarkParams; import org.openjdk.jmh.infra.Control; import org.openjdk.jmh.infra.IterationParams; import org.openjdk.jmh.infra.ThreadParams; import org.openjdk.jmh.profile.InternalProfiler; import org.openjdk.jmh.profile.ProfilerFactory; import org.openjdk.jmh.results.*; import org.openjdk.jmh.runner.format.OutputFormat; import org.openjdk.jmh.runner.options.Options; import org.openjdk.jmh.runner.options.TimeValue; import org.openjdk.jmh.util.ClassUtils; import org.openjdk.jmh.util.Utils; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.util.*; import java.util.concurrent.*; /** * Base class for all benchmarks handlers. */ class BenchmarkHandler { /** * Thread-pool for threads executing the benchmark tasks */ private final ExecutorService executor; private final CyclicBarrier workerDataBarrier; private final ConcurrentMap<Thread, WorkerData> workerData; private final BlockingQueue<WorkerData> unusedWorkerData; private final BlockingQueue<ThreadParams> tps; private final OutputFormat out; private final List<InternalProfiler> profilers; private final List<InternalProfiler> profilersRev; private final Class<?> clazz; private final Method method; public BenchmarkHandler(OutputFormat out, Options options, BenchmarkParams executionParams) { String target = executionParams.generatedBenchmark(); int lastDot = target.lastIndexOf('.'); clazz = ClassUtils.loadClass(target.substring(0, lastDot)); method = BenchmarkHandler.findBenchmarkMethod(clazz, target.substring(lastDot + 1)); profilers = ProfilerFactory.getSupportedInternal(options.getProfilers()); profilersRev = new ArrayList<>(profilers); Collections.reverse(profilersRev); int threads = executionParams.getThreads(); tps = new ArrayBlockingQueue<>(threads); tps.addAll(distributeThreads(threads, executionParams.getThreadGroups())); workerDataBarrier = new CyclicBarrier(threads, this::captureUnusedWorkerData); workerData = new ConcurrentHashMap<>(); unusedWorkerData = new ArrayBlockingQueue<>(threads); this.out = out; try { executor = EXECUTOR_TYPE.createExecutor(threads, executionParams.getBenchmark()); } catch (Exception e) { throw new IllegalStateException(e); } } static List<ThreadParams> distributeThreads(int threads, int[] groups) { List<ThreadParams> result = new ArrayList<>(); int totalGroupThreads = Utils.sum(groups); int totalGroups = (int) Math.ceil(1D * threads / totalGroupThreads); int totalSubgroups = groups.length; int currentGroupThread = 0; int currentSubgroupThread = 0; int currentGroup = 0; int currentSubgroup = 0; for (int t = 0; t < threads; t++) { while (currentSubgroupThread >= groups[currentSubgroup]) { currentSubgroup++; if (currentSubgroup == groups.length) { currentGroup++; currentSubgroup = 0; currentGroupThread = 0; } currentSubgroupThread = 0; } result.add(new ThreadParams( t, threads, currentGroup, totalGroups, currentSubgroup, totalSubgroups, currentGroupThread, totalGroupThreads, currentSubgroupThread, groups[currentSubgroup] ) ); currentGroupThread++; currentSubgroupThread++; } return result; } public static Method findBenchmarkMethod(Class<?> clazz, String methodName) { Method method = null; for (Method m : ClassUtils.enumerateMethods(clazz)) { if (m.getName().equals(methodName)) { if (isValidBenchmarkSignature(m)) { if (method != null) { throw new IllegalArgumentException("Ambiguous methods: \n" + method + "\n and \n" + m + "\n, which one to execute?"); } method = m; } else { throw new IllegalArgumentException("Benchmark parameters do not match the signature contract."); } } } if (method == null) { throw new IllegalArgumentException("No matching methods found in benchmark"); } return method; } /** * checks if method signature is valid benchmark signature, * besited checks if method signature corresponds to benchmark type. * @param m * @return */ private static boolean isValidBenchmarkSignature(Method m) { if (m.getReturnType() != BenchmarkTaskResult.class) { return false; } final Class<?>[] parameterTypes = m.getParameterTypes(); if (parameterTypes.length != 2) { return false; } if (parameterTypes[0] != InfraControl.class) { return false; } if (parameterTypes[1] != ThreadParams.class) { return false; } return true; } private static final ExecutorType EXECUTOR_TYPE = Enum.valueOf(ExecutorType.class, System.getProperty("jmh.executor", ExecutorType.PLATFORM.name())); private enum ExecutorType { /** * Use fixed thread pool with platform threads */ PLATFORM { @Override ExecutorService createExecutor(int maxThreads, String prefix) { return Executors.newFixedThreadPool(maxThreads, WorkerThreadFactories.platformWorkerFactory(prefix)); } @Override boolean stableThreads() { return true; } }, /** * Use fixed thread pool with virtual threads */ VIRTUAL { @Override ExecutorService createExecutor(int maxThreads, String prefix) { return Executors.newFixedThreadPool(maxThreads, WorkerThreadFactories.virtualWorkerFactory(prefix)); } @Override boolean shouldYield() { return true; } }, /** * Use ForkJoinPool */ FJP { @Override ExecutorService createExecutor(int maxThreads, String prefix) { return new ForkJoinPool(maxThreads); } }, /** * Use custom executor */ CUSTOM { @Override ExecutorService createExecutor(int maxThreads, String prefix) throws Exception { String className = System.getProperty("jmh.executor.class"); return (ExecutorService) Class.forName(className).getConstructor(int.class, String.class) .newInstance(maxThreads, prefix); } }, ; abstract ExecutorService createExecutor(int maxThreads, String prefix) throws Exception; /** * @return Executor always reuses the same threads? */ boolean stableThreads() { return false; } /** * @return Executing threads should yield occasionally to guarantee progress? */ boolean shouldYield() { return false; } } protected void startProfilers(BenchmarkParams benchmarkParams, IterationParams iterationParams) { // start profilers for (InternalProfiler prof : profilers) { try { prof.beforeIteration(benchmarkParams, iterationParams); } catch (Throwable ex) { throw new BenchmarkException(ex); } } } protected void stopProfilers(BenchmarkParams benchmarkParams, IterationParams iterationParams, IterationResult iterationResults) { // stop profilers for (InternalProfiler prof : profilersRev) { try { iterationResults.addResults(prof.afterIteration(benchmarkParams, iterationParams, iterationResults)); } catch (Throwable ex) { throw new BenchmarkException(ex); } } } /** * Do required shutdown actions. */ public void shutdown() { // No transient data is shared between benchmarks, purge it. workerData.clear(); if (executor == null) { return; } while (true) { executor.shutdown(); try { if (executor.awaitTermination(10, TimeUnit.SECONDS)) { return; } } catch (InterruptedException e) { Thread.currentThread().interrupt(); return; } out.println("Failed to stop executor service " + executor + ", trying again; check for the unaccounted running threads"); } } /** * Runs an iteration on the handled benchmark. * * @param benchmarkParams Benchmark parameters * @param params Iteration parameters * @param isFirstIteration Should this iteration considered to be the first * @param isLastIteration Should this iteration considered to be the last * @return IterationResult */ public IterationResult runIteration(BenchmarkParams benchmarkParams, IterationParams params, boolean isFirstIteration, boolean isLastIteration) { int numThreads = benchmarkParams.getThreads(); TimeValue runtime = params.getTime(); CountDownLatch preSetupBarrier = new CountDownLatch(numThreads); CountDownLatch preTearDownBarrier = new CountDownLatch(numThreads); // result object to accumulate the results in List<Result> iterationResults = new ArrayList<>(); InfraControl control = new InfraControl(benchmarkParams, params, preSetupBarrier, preTearDownBarrier, isFirstIteration, isLastIteration, EXECUTOR_TYPE.shouldYield(), new Control()); // preparing the worker runnables BenchmarkTask[] runners = new BenchmarkTask[numThreads]; for (int i = 0; i < runners.length; i++) { runners[i] = new BenchmarkTask(control); } long waitDeadline = System.nanoTime() + benchmarkParams.getTimeout().convertTo(TimeUnit.NANOSECONDS); // profilers start way before the workload starts to capture // the edge behaviors. startProfilers(benchmarkParams, params); // submit tasks to threadpool List<Future<BenchmarkTaskResult>> completed = new ArrayList<>(); CompletionService<BenchmarkTaskResult> srv = new ExecutorCompletionService<>(executor); for (BenchmarkTask runner : runners) { srv.submit(runner); } // wait for all workers to transit to measurement control.awaitWarmupReady(); // wait for the iteration time to expire switch (benchmarkParams.getMode()) { case SingleShotTime: // don't wait here, block on timed result Future break; default: try { Future<BenchmarkTaskResult> failing = srv.poll(runtime.convertTo(TimeUnit.NANOSECONDS), TimeUnit.NANOSECONDS); if (failing != null) { // Oops, some task has exited prematurely, without isDone check. // Must be an exception. Record the failing result, and lift the // timeout deadline: we care only to exit as fast as possible now. completed.add(failing); waitDeadline = System.nanoTime(); } } catch (InterruptedException e) { // regardless... } } // now we communicate all worker threads should stop control.announceDone(); // wait for all workers to transit to teardown control.awaitWarmdownReady(); // Wait for the result, handling timeouts int interrupts = 0; while (completed.size() < numThreads) { try { long waitFor = Math.max(TimeUnit.MILLISECONDS.toNanos(100), waitDeadline - System.nanoTime()); Future<BenchmarkTaskResult> fr = srv.poll(waitFor, TimeUnit.NANOSECONDS); if (fr == null) { // We are in the timeout mode now, kick all the still running threads. for (BenchmarkTask task : runners) { Thread runner = task.runner; if (runner != null) { runner.interrupt(); } } interrupts++; } else { completed.add(fr); } } catch (InterruptedException ex) { throw new BenchmarkException(ex); } } if (interrupts > 0) { out.print("(benchmark timed out, interrupted " + interrupts + " times) "); } // Process the results: we get here after all worker threads have quit, // either normally or abnormally. This means, Future.get() would never block. long allOps = 0; long measuredOps = 0; List<Throwable> errors = new ArrayList<>(); for (Future<BenchmarkTaskResult> fr : completed) { try { BenchmarkTaskResult btr = fr.get(); iterationResults.addAll(btr.getResults()); allOps += btr.getAllOps(); measuredOps += btr.getMeasuredOps(); } catch (ExecutionException ex) { // Unwrap at most three exceptions through benchmark-thrown exception: // ExecutionException -> Throwable-wrapper -> InvocationTargetException // // Infrastructural exceptions come with shorter causal chains. Throwable cause = ex; for (int c = 0; (c < 3) && (cause.getCause() != null); c++) { cause = cause.getCause(); } // record exception, unless it is the assist exception if (!(cause instanceof FailureAssistException)) { errors.add(cause); } } catch (InterruptedException ex) { // cannot happen here, Future.get() should never block. throw new BenchmarkException(ex); } } IterationResult result = new IterationResult(benchmarkParams, params, new IterationResultMetaData(allOps, measuredOps)); result.addResults(iterationResults); // profilers stop when after all threads are confirmed to be // finished to capture the edge behaviors; or, on a failure path stopProfilers(benchmarkParams, params, result); if (!errors.isEmpty()) { throw new BenchmarkException("Benchmark error during the run", errors); } return result; } private WorkerData getWorkerData(Thread worker) throws Exception { // See if there is a good worker data for us already, use it. WorkerData wd = workerData.remove(worker); // Wait for all threads to roll to this synchronization point. // If there is any thread without assignment, the barrier action // would dump the unused worker data for claiming. workerDataBarrier.await(); if (wd == null) { // Odd mode, no worker task recorded for the thread. Pull the worker data // from the unused queue. This can only happen with executors with unstable threads. if (EXECUTOR_TYPE.stableThreads()) { throw new IllegalStateException("Worker data assignment failed for executor with stable threads"); } wd = unusedWorkerData.poll(); if (wd == null) { throw new IllegalStateException("Cannot get another thread working data"); } } WorkerData exist = workerData.put(worker, wd); if (exist != null) { throw new IllegalStateException("Duplicate thread data"); } return wd; } private void captureUnusedWorkerData() { unusedWorkerData.addAll(workerData.values()); workerData.clear(); } private WorkerData newWorkerData(Thread worker) { try { Object o = clazz.getConstructor().newInstance(); ThreadParams t = tps.poll(); if (t == null) { throw new IllegalStateException("Cannot get another thread params"); } WorkerData wd = new WorkerData(o, t); WorkerData exist = workerData.put(worker, wd); if (exist != null) { throw new IllegalStateException("Duplicate thread data"); } return wd; } catch (InstantiationException | IllegalAccessException | NoSuchMethodException | InvocationTargetException e) { throw new RuntimeException("Class " + clazz.getName() + " instantiation error ", e); } } /** * Worker body. */ class BenchmarkTask implements Callable<BenchmarkTaskResult> { private volatile Thread runner; private final InfraControl control; BenchmarkTask(InfraControl control) { this.control = control; } @Override public BenchmarkTaskResult call() throws Exception { try { // bind the executor thread runner = Thread.currentThread(); // Clear the interruption status for the thread before going into the infra. // Normally, the interrupts would be cleared at the end of benchmark, but // there is a tiny window when harness could deliver another interrupt after // we left. boolean unused = Thread.interrupted(); // poll the current data, or instantiate in this thread, if needed WorkerData wd = control.firstIteration ? newWorkerData(runner) : getWorkerData(runner); return (BenchmarkTaskResult) method.invoke(wd.instance, control, wd.params); } catch (Throwable e) { // about to fail the iteration; // notify other threads we have failed control.isFailing = true; // compensate for missed sync-iteration latches, we don't care about that anymore control.preSetupForce(); control.preTearDownForce(); if (control.benchmarkParams.shouldSynchIterations()) { try { control.announceWarmupReady(); } catch (Exception e1) { // more threads than expected } try { control.announceWarmdownReady(); } catch (Exception e1) { // more threads than expected } } throw new Exception(e); // wrapping Throwable } finally { // unbind the executor thread runner = null; // Clear the interruption status for the thread after leaving the benchmark method. // If any InterruptedExceptions happened, they should have been handled by now. // This prepares the runner thread for another iteration. boolean unused = Thread.interrupted(); } } } /** * Handles thread-local data for each worker that should not change * between the iterations. */ private static class WorkerData { /** * Synthetic benchmark instance, which holds the benchmark metadata. * Expected to be touched by a single thread only. */ final Object instance; /** * Thread parameters. Among other things, holds the thread's place * in group distribution, and thus should be the same for a given thread. */ final ThreadParams params; public WorkerData(Object instance, ThreadParams params) { this.instance = instance; this.params = params; } } }
21,915
36.145763
153
java
jmh
jmh-master/jmh-core/src/main/java/org/openjdk/jmh/runner/BenchmarkList.java
/* * Copyright (c) 2005, 2013, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package org.openjdk.jmh.runner; import org.openjdk.jmh.runner.format.OutputFormat; import org.openjdk.jmh.util.FileUtils; import java.io.*; import java.nio.charset.StandardCharsets; import java.util.*; import java.util.regex.Pattern; /** * Helper class for listing micro benchmarks. */ public class BenchmarkList extends AbstractResourceReader { /** Location of the pre-compiled list of micro benchmarks */ public static final String BENCHMARK_LIST = "/META-INF/BenchmarkList"; public static BenchmarkList defaultList() { return fromResource(BENCHMARK_LIST); } public static BenchmarkList fromFile(String file) { return new BenchmarkList(file, null, null); } public static BenchmarkList fromResource(String resource) { return new BenchmarkList(null, resource, null); } public static BenchmarkList fromString(String strings) { return new BenchmarkList(null, null, strings); } public static List<BenchmarkListEntry> readBenchmarkList(InputStream stream) throws IOException { try (Reader reader = new InputStreamReader(stream, StandardCharsets.UTF_8)) { List<BenchmarkListEntry> entries = new ArrayList<>(); for (String line : FileUtils.readAllLines(reader)) { BenchmarkListEntry ble = new BenchmarkListEntry(line); entries.add(ble); } return entries; } } public static void writeBenchmarkList(OutputStream stream, Collection<BenchmarkListEntry> entries) { try (PrintWriter writer = new PrintWriter(new OutputStreamWriter(stream, StandardCharsets.UTF_8))) { List<BenchmarkListEntry> sorted = new ArrayList<>(entries); Collections.sort(sorted); for (BenchmarkListEntry entry : sorted) { writer.println(entry.toLine()); } } } private BenchmarkList(String file, String resource, String strings) { super(file, resource, strings); } /** * Gets all micro benchmarks from the list, sorted. * * @param out Output the messages here * @param excludes List of regexps to match excludes against * @return A list of all benchmarks, excluding matched */ public Set<BenchmarkListEntry> getAll(OutputFormat out, List<String> excludes) { return find(out, Collections.singletonList(".*"), excludes); } /** * Gets all the micro benchmarks that matches the given regexp, sorted. * * @param out Output the messages here * @param includes List of regexps to match against * @param excludes List of regexps to match excludes against * @return Names of all micro benchmarks in the list that matches includes and NOT matching excludes */ public SortedSet<BenchmarkListEntry> find(OutputFormat out, List<String> includes, List<String> excludes) { // assume we match all benchmarks when include is empty List<String> regexps = new ArrayList<>(includes); if (regexps.isEmpty()) { regexps.add(Defaults.INCLUDE_BENCHMARKS); } // compile all patterns List<Pattern> includePatterns = new ArrayList<>(regexps.size()); for (String regexp : regexps) { includePatterns.add(Pattern.compile(regexp)); } List<Pattern> excludePatterns = new ArrayList<>(excludes.size()); for (String regexp : excludes) { excludePatterns.add(Pattern.compile(regexp)); } // find all benchmarks containing pattern SortedSet<BenchmarkListEntry> result = new TreeSet<>(); try { for (Reader r : getReaders()) { try (BufferedReader reader = new BufferedReader(r)) { for (String line = reader.readLine(); line != null; line = reader.readLine()) { if (line.startsWith("#")) { continue; } if (line.trim().isEmpty()) { continue; } BenchmarkListEntry br = new BenchmarkListEntry(line); for (Pattern pattern : includePatterns) { if (pattern.matcher(br.getUsername()).find()) { boolean exclude = false; // excludes override for (Pattern excludePattern : excludePatterns) { if (excludePattern.matcher(br.getUsername()).find()) { out.verbosePrintln("Excluding " + br.getUsername() + ", matches " + excludePattern); exclude = true; break; } } if (!exclude) { result.add(br); } break; } else { out.verbosePrintln("Excluding: " + br.getUsername() + ", does not match " + pattern); } } } } } } catch (IOException ex) { throw new RuntimeException("Error reading benchmark list", ex); } return result; } }
6,714
38.269006
124
java
jmh
jmh-master/jmh-core/src/main/java/org/openjdk/jmh/runner/BenchmarkListEntry.java
/* * Copyright (c) 2005, 2013, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package org.openjdk.jmh.runner; import org.openjdk.jmh.annotations.Mode; import org.openjdk.jmh.runner.options.TimeValue; import org.openjdk.jmh.util.Optional; import org.openjdk.jmh.util.lines.TestLineReader; import org.openjdk.jmh.util.lines.TestLineWriter; import java.util.Arrays; import java.util.Collection; import java.util.Map; import java.util.Objects; import java.util.concurrent.TimeUnit; public class BenchmarkListEntry implements Comparable<BenchmarkListEntry> { private final String userClassQName; private final String generatedClassQName; private final String method; private final Mode mode; private final int[] threadGroups; private final Optional<Collection<String>> threadGroupLabels; private final Optional<Integer> threads; private final Optional<Integer> warmupIterations; private final Optional<TimeValue> warmupTime; private final Optional<Integer> warmupBatchSize; private final Optional<Integer> measurementIterations; private final Optional<TimeValue> measurementTime; private final Optional<Integer> measurementBatchSize; private final Optional<Integer> forks; private final Optional<Integer> warmupForks; private final Optional<String> jvm; private final Optional<Collection<String>> jvmArgs; private final Optional<Collection<String>> jvmArgsPrepend; private final Optional<Collection<String>> jvmArgsAppend; private final Optional<Map<String, String[]>> params; private final Optional<TimeUnit> tu; private final Optional<Integer> opsPerInvocation; private final Optional<TimeValue> timeout; private WorkloadParams workloadParams; public BenchmarkListEntry(String userClassQName, String generatedClassQName, String method, Mode mode, Optional<Integer> threads, int[] threadGroups, Optional<Collection<String>> threadGroupLabels, Optional<Integer> warmupIterations, Optional<TimeValue> warmupTime, Optional<Integer> warmupBatchSize, Optional<Integer> measurementIterations, Optional<TimeValue> measurementTime, Optional<Integer> measurementBatchSize, Optional<Integer> forks, Optional<Integer> warmupForks, Optional<String> jvm, Optional<Collection<String>> jvmArgs, Optional<Collection<String>> jvmArgsPrepend, Optional<Collection<String>> jvmArgsAppend, Optional<Map<String, String[]>> params, Optional<TimeUnit> tu, Optional<Integer> opsPerInv, Optional<TimeValue> timeout) { this.userClassQName = userClassQName; this.generatedClassQName = generatedClassQName; this.method = method; this.mode = mode; this.threadGroups = threadGroups; this.threads = threads; this.threadGroupLabels = threadGroupLabels; this.warmupIterations = warmupIterations; this.warmupTime = warmupTime; this.warmupBatchSize = warmupBatchSize; this.measurementIterations = measurementIterations; this.measurementTime = measurementTime; this.measurementBatchSize = measurementBatchSize; this.forks = forks; this.warmupForks = warmupForks; this.jvm = jvm; this.jvmArgs = jvmArgs; this.jvmArgsPrepend = jvmArgsPrepend; this.jvmArgsAppend = jvmArgsAppend; this.params = params; this.workloadParams = new WorkloadParams(); this.tu = tu; this.opsPerInvocation = opsPerInv; this.timeout = timeout; } public BenchmarkListEntry(String line) { this.workloadParams = new WorkloadParams(); TestLineReader reader = new TestLineReader(line); if (!reader.isCorrect()) { throw new IllegalStateException("Unable to parse the line: " + line); } this.userClassQName = reader.nextString(); this.generatedClassQName = reader.nextString(); this.method = reader.nextString(); this.mode = Mode.deepValueOf(reader.nextString()); this.threads = reader.nextOptionalInt(); this.threadGroups = reader.nextIntArray(); this.threadGroupLabels = reader.nextOptionalStringCollection(); this.warmupIterations = reader.nextOptionalInt(); this.warmupTime = reader.nextOptionalTimeValue(); this.warmupBatchSize = reader.nextOptionalInt(); this.measurementIterations = reader.nextOptionalInt(); this.measurementTime = reader.nextOptionalTimeValue(); this.measurementBatchSize = reader.nextOptionalInt(); this.forks = reader.nextOptionalInt(); this.warmupForks = reader.nextOptionalInt(); this.jvm = reader.nextOptionalString(); this.jvmArgs = reader.nextOptionalStringCollection(); this.jvmArgsPrepend = reader.nextOptionalStringCollection(); this.jvmArgsAppend = reader.nextOptionalStringCollection(); this.params = reader.nextOptionalParamCollection(); this.tu = reader.nextOptionalTimeUnit(); this.opsPerInvocation = reader.nextOptionalInt(); this.timeout = reader.nextOptionalTimeValue(); } public String toLine() { TestLineWriter writer = new TestLineWriter(); writer.putString(userClassQName); writer.putString(generatedClassQName); writer.putString(method); writer.putString(mode.toString()); writer.putOptionalInt(threads); writer.putIntArray(threadGroups); writer.putOptionalStringCollection(threadGroupLabels); writer.putOptionalInt(warmupIterations); writer.putOptionalTimeValue(warmupTime); writer.putOptionalInt(warmupBatchSize); writer.putOptionalInt(measurementIterations); writer.putOptionalTimeValue(measurementTime); writer.putOptionalInt(measurementBatchSize); writer.putOptionalInt(forks); writer.putOptionalInt(warmupForks); writer.putOptionalString(jvm); writer.putOptionalStringCollection(jvmArgs); writer.putOptionalStringCollection(jvmArgsPrepend); writer.putOptionalStringCollection(jvmArgsAppend); writer.putOptionalParamCollection(params); writer.putOptionalTimeUnit(tu); writer.putOptionalInt(opsPerInvocation); writer.putOptionalTimeValue(timeout); return writer.toString(); } public BenchmarkListEntry cloneWith(Mode mode) { return new BenchmarkListEntry(userClassQName, generatedClassQName, method, mode, threads, threadGroups, threadGroupLabels, warmupIterations, warmupTime, warmupBatchSize, measurementIterations, measurementTime, measurementBatchSize, forks, warmupForks, jvm, jvmArgs, jvmArgsPrepend, jvmArgsAppend, params, tu, opsPerInvocation, timeout); } public BenchmarkListEntry cloneWith(WorkloadParams p) { BenchmarkListEntry br = new BenchmarkListEntry(userClassQName, generatedClassQName, method, mode, threads, threadGroups, threadGroupLabels, warmupIterations, warmupTime, warmupBatchSize, measurementIterations, measurementTime, measurementBatchSize, forks, warmupForks, jvm, jvmArgs, jvmArgsPrepend, jvmArgsAppend, params, tu, opsPerInvocation, timeout); br.workloadParams = p; return br; } public WorkloadParams getWorkloadParams() { return workloadParams; } @Override public int compareTo(BenchmarkListEntry o) { int v = mode.compareTo(o.mode); if (v != 0) { return v; } int v1 = getUsername().compareTo(o.getUsername()); if (v1 != 0) { return v1; } if (workloadParams == null || o.workloadParams == null) { return 0; } return workloadParams.compareTo(o.workloadParams); } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; BenchmarkListEntry record = (BenchmarkListEntry) o; if (mode != record.mode) return false; if (!Objects.equals(workloadParams, record.workloadParams)) return false; if (!Objects.equals(userClassQName, record.userClassQName)) return false; if (!Objects.equals(method, record.method)) return false; return true; } @Override public int hashCode() { int result = userClassQName != null ? userClassQName.hashCode() : 0; result = 31 * result + (method != null ? method.hashCode() : 0); result = 31 * result + (mode != null ? mode.hashCode() : 0); result = 31 * result + (workloadParams != null ? workloadParams.hashCode() : 0); return result; } public String generatedTarget() { return generatedClassQName + "." + method + "_" + mode; } public String getUsername() { return userClassQName + "." + method; } public String getUserClassQName() { return userClassQName; } public Mode getMode() { return mode; } public int[] getThreadGroups() { return Arrays.copyOf(threadGroups, threadGroups.length); } public Optional<Collection<String>> getThreadGroupLabels() { return threadGroupLabels; } @Override public String toString() { return "{'" + userClassQName + "." + method + "', " + mode + ", " + workloadParams + "}"; } public Optional<TimeValue> getWarmupTime() { return warmupTime; } public Optional<Integer> getWarmupIterations() { return warmupIterations; } public Optional<Integer> getWarmupBatchSize() { return warmupBatchSize; } public Optional<TimeValue> getMeasurementTime() { return measurementTime; } public Optional<Integer> getMeasurementIterations() { return measurementIterations; } public Optional<Integer> getMeasurementBatchSize() { return measurementBatchSize; } public Optional<Integer> getForks() { return forks; } public Optional<Integer> getWarmupForks() { return warmupForks; } public Optional<String> getJvm() { return jvm; } public Optional<Collection<String>> getJvmArgs() { return jvmArgs; } public Optional<Collection<String>> getJvmArgsAppend() { return jvmArgsAppend; } public Optional<Collection<String>> getJvmArgsPrepend() { return jvmArgsPrepend; } public Optional<Integer> getThreads() { return threads; } public Optional<Map<String, String[]>> getParams() { return params; } public Optional<TimeUnit> getTimeUnit() { return tu; } public Optional<Integer> getOperationsPerInvocation() { return opsPerInvocation; } public Optional<TimeValue> getTimeout() { return timeout; } }
12,609
36.754491
178
java
jmh
jmh-master/jmh-core/src/main/java/org/openjdk/jmh/runner/CompilerHints.java
/* * Copyright (c) 2005, 2013, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package org.openjdk.jmh.runner; import org.openjdk.jmh.util.FileUtils; import org.openjdk.jmh.util.Utils; import java.io.*; import java.util.*; public class CompilerHints extends AbstractResourceReader { public static final String LIST = "/META-INF/CompilerHints"; // All OpenJDK/HotSpot VMs are supported static final String[] HINT_COMPATIBLE_JVMS = { "OpenJDK", "HotSpot", "GraalVM" }; // Zing is only compatible from post 5.10.*.* releases static final String JVM_ZING = "Zing"; private static volatile CompilerHints defaultList; private static volatile String hintsFile; private final Set<String> hints; static final String XX_COMPILE_COMMAND_FILE = "-XX:CompileCommandFile="; static final String BLACKHOLE_MODE_NAME = "jmh.blackhole.mode"; static final String BLACKHOLE_AUTODETECT_NAME = "jmh.blackhole.autoDetect"; static final String BLACKHOLE_DEBUG_NAME = "jmh.blackhole.debug"; static final String COMPILER_HINTS_MODE = "jmh.compilerhints.mode"; static final boolean BLACKHOLE_MODE_AUTODETECT = Boolean.parseBoolean(System.getProperty(BLACKHOLE_AUTODETECT_NAME, "true")); static final boolean BLACKHOLE_MODE_DEBUG = Boolean.parseBoolean(System.getProperty(BLACKHOLE_DEBUG_NAME, "false")); public static CompilerHints defaultList() { if (defaultList == null) { defaultList = fromResource(LIST); } return defaultList; } public static String hintsFile() { if (hintsFile == null) { try { final Set<String> defaultHints = defaultList().get(); List<String> hints = new ArrayList<>(defaultHints.size() + 2); hints.add("quiet"); // Set up Blackholes BlackholeMode bhMode = blackholeMode(); hints.add("inline,org/openjdk/jmh/infra/Blackhole.consume"); hints.add("dontinline,org/openjdk/jmh/infra/Blackhole.consumeCPU"); if (bhMode.shouldBlackhole()) { hints.add("blackhole,org/openjdk/jmh/infra/Blackhole.consumeCompiler"); } if (bhMode.shouldNotInline()) { hints.add("dontinline,org/openjdk/jmh/infra/Blackhole.consumeFull"); } hints.addAll(defaultHints); hintsFile = FileUtils.createTempFileWithLines("compilecommand", hints); } catch (IOException e) { throw new IllegalStateException("Error creating compiler hints file", e); } } return hintsFile; } public static CompilerHints fromResource(String resource) { return new CompilerHints(null, resource); } public static CompilerHints fromFile(String file) { return new CompilerHints(file, null); } private CompilerHints(String file, String resource) { super(file, resource, null); hints = Collections.unmodifiableSet(read()); } public enum CompilerHintsSelect { FORCE_ON("Forced on", false, true), FORCE_OFF("Forced off", false, false), AUTO_ON("Automatically enabled", true, true), AUTO_OFF("Automatically disabled", true, false); private final String desc; private final boolean auto; private final boolean enabled; CompilerHintsSelect(String desc, boolean auto, boolean enabled) { this.desc = desc; this.auto = auto; this.enabled = enabled; } public String desc() { return desc; } public boolean isAuto() { return auto; } public boolean isEnabled() { return enabled; } } static CompilerHintsSelect compilerHintsSelect; public static CompilerHintsSelect compilerHintsSelect() { if (compilerHintsSelect == null) { compilerHintsSelect = checkCompilerHintsState(); } return compilerHintsSelect; } static void resetCompilerHintsSelect() { // only used by tests compilerHintsSelect = null; } private static boolean compilerHintsEnabled() { return compilerHintsSelect().isEnabled(); } /** * FIXME (low priority): check if supplied JVM is hint compatible. This test is applied to the Runner VM, * not the Forked and may therefore be wrong if the forked VM is not the same JVM */ private static CompilerHintsSelect checkCompilerHintsState() { String propMode = System.getProperty(COMPILER_HINTS_MODE); if (propMode != null) { CompilerHintsSelect forced; try { forced = CompilerHintsSelect.valueOf(propMode); } catch (IllegalArgumentException e) { throw new IllegalArgumentException(COMPILER_HINTS_MODE + " should be set to FORCE_ON or FORCE_OFF", e); } if (forced.isAuto()) { throw new IllegalArgumentException(COMPILER_HINTS_MODE + " should be set to FORCE_ON or FORCE_OFF"); } return forced; } String name = System.getProperty("java.vm.name"); for (String vmName : HINT_COMPATIBLE_JVMS) { if (name.contains(vmName)) { return CompilerHintsSelect.AUTO_ON; } } if (name.contains(JVM_ZING)) { // 1.*.0-zing_*.*.*.* String version = System.getProperty("java.version"); try { // get the version digits String[] versionDigits = version.substring(version.indexOf('_') + 1).split("\\."); if (Integer.parseInt(versionDigits[0]) > 5) { return CompilerHintsSelect.AUTO_ON; } else if (Integer.parseInt(versionDigits[0]) == 5 && Integer.parseInt(versionDigits[1]) >= 10) { return CompilerHintsSelect.AUTO_ON; } } catch (NumberFormatException | ArrayIndexOutOfBoundsException e) { // unknown Zing version format System.err.println("ERROR: Zing version format does not match 1.*.0-zing_*.*.*.*"); } } return CompilerHintsSelect.AUTO_OFF; } public Set<String> get() { return hints; } private Set<String> read() { Set<String> result = new TreeSet<>(); try { for (Reader r : getReaders()) { try (BufferedReader reader = new BufferedReader(r)) { for (String line = reader.readLine(); line != null; line = reader.readLine()) { if (line.startsWith("#")) { continue; } if (line.trim().isEmpty()) { continue; } result.add(line); } } } } catch (IOException ex) { throw new RuntimeException("Error reading compiler hints", ex); } return result; } /** * @param command command arguments list * @return the compiler hint files specified by the command */ public static List<String> getCompileCommandFiles(List<String> command){ List<String> compileCommandFiles = new ArrayList<>(); for (String cmdLineWord : command) { if (cmdLineWord.startsWith(XX_COMPILE_COMMAND_FILE)) { compileCommandFiles.add(cmdLineWord.substring(XX_COMPILE_COMMAND_FILE.length())); } } return compileCommandFiles; } /** * We need to generate a compiler hints file such that it includes: * <ul> * <li> No compile command files are specified and no .hotspotrc file is available, then do JMH hints only * <li> No compile command files are specified and .hotspotrc file is available, then do JMH hints + .hotspotrc * <li> 1 to N compile command files are specified, then do JMH hints + all specified hints in files * </ul> * <p>This is a departure from default JVM behavior as the JVM would normally just take the last hints file and ignore * the rest. * * @param command all -XX:CompileCommandLine args will be removed and a merged file will be set */ public static void addCompilerHints(List<String> command) { if (compilerHintsSelect() == CompilerHintsSelect.AUTO_OFF) { System.err.println("WARNING: Not a HotSpot compiler command compatible VM (\"" + System.getProperty("java.vm.name") + "-" + System.getProperty("java.version") + "\"), compiler hints are disabled."); } if (!compilerHintsEnabled()) { return; } List<String> hintFiles = new ArrayList<>(); hintFiles.add(hintsFile()); removeCompileCommandFiles(command, hintFiles); if (hintFiles.size() == 1) { File hotspotCompilerFile = new File(".hotspot_compiler"); if (hotspotCompilerFile.exists()) { hintFiles.add(hotspotCompilerFile.getAbsolutePath()); } } if (blackholeMode() == BlackholeMode.COMPILER) { command.add("-XX:+UnlockDiagnosticVMOptions"); command.add("-XX:+UnlockExperimentalVMOptions"); command.add("-DcompilerBlackholesEnabled=true"); } command.add(CompilerHints.XX_COMPILE_COMMAND_FILE + mergeHintFiles(hintFiles)); } /** * @param command the compile command file options will be removed from this command * @param compileCommandFiles the compiler hint files specified by the command will be added to this list */ private static void removeCompileCommandFiles(List<String> command, List<String> compileCommandFiles){ Iterator<String> iterator = command.iterator(); while (iterator.hasNext()) { String cmdLineWord = iterator.next(); if(cmdLineWord.startsWith(XX_COMPILE_COMMAND_FILE)) { compileCommandFiles.add(cmdLineWord.substring(XX_COMPILE_COMMAND_FILE.length())); iterator.remove(); } } } private static String mergeHintFiles(List<String> compileCommandFiles) { if (compileCommandFiles.size() == 1) { return compileCommandFiles.get(0); } try { Set<String> hints = new TreeSet<>(); for(String file : compileCommandFiles) { hints.addAll(fromFile(file).get()); } return FileUtils.createTempFileWithLines("compilecommand", hints); } catch (IOException e) { throw new IllegalStateException("Error merging compiler hints files", e); } } private static BlackholeMode blackholeMode; private static BlackholeSelect blackholeSelect; private static BlackholeMode blackholeMode() { if (blackholeMode != null) { return blackholeMode; } // Forced mode takes precedence. String propMode = System.getProperty(BLACKHOLE_MODE_NAME); if (propMode != null) { try { blackholeMode = BlackholeMode.valueOf(propMode); blackholeSelect = BlackholeSelect.FORCED; // Extra safety: If user requested compiler blackholes, check // if they are available and fail otherwise. if (blackholeMode.shouldBlackhole() && !compilerBlackholesAvailable()) { throw new IllegalStateException("Compiler Blackholes are not available in current VM"); } return blackholeMode; } catch (IllegalArgumentException iae) { throw new IllegalStateException("Unknown Blackhole mode: " + propMode); } } // Try to autodetect blackhole mode, fail if not available if (BLACKHOLE_MODE_AUTODETECT) { if (compilerBlackholesAvailable()) { blackholeMode = BlackholeMode.COMPILER; } else { blackholeMode = BlackholeMode.FULL_DONTINLINE; } blackholeSelect = BlackholeSelect.AUTO; return blackholeMode; } // Not forced, not auto-detected, fallback blackholeMode = BlackholeMode.FULL_DONTINLINE; blackholeSelect = BlackholeSelect.FALLBACK; return blackholeMode; } private static BlackholeSelect blackholeSelect() { blackholeMode(); return blackholeSelect; } private enum BlackholeMode { COMPILER(true, false, "compiler"), FULL_DONTINLINE(false, true, "full + dont-inline hint"), FULL(false, false, "full"), ; private final boolean shouldBlackhole; private final boolean shouldNotInline; private final String desc; BlackholeMode(boolean shouldBlackhole, boolean shouldNotInline, String desc) { this.shouldBlackhole = shouldBlackhole; this.shouldNotInline = shouldNotInline; this.desc = desc; } public boolean shouldBlackhole() { return shouldBlackhole; } public boolean shouldNotInline() { return shouldNotInline; } public String desc() { return desc; } } private enum BlackholeSelect { AUTO("auto-detected, use -D" + BLACKHOLE_AUTODETECT_NAME + "=false to disable"), FALLBACK("fallback, use -D" + BLACKHOLE_MODE_NAME + " to force"), FORCED("forced"), ; final String desc; BlackholeSelect(String desc) { this.desc = desc; } public String desc() { return desc; } } private static boolean compilerBlackholesAvailable() { // Step 1. See if there were any error messages from CompilerOracle { List<String> cmd = new ArrayList<>(); cmd.add(Utils.getCurrentJvm()); cmd.add("-XX:+UnlockExperimentalVMOptions"); cmd.add("-XX:CompileCommand=quiet"); cmd.add("-XX:CompileCommand=blackhole,some/fake/Class.method"); cmd.add("-version"); debug("Blackhole command errors test:"); Collection<String> log = Utils.runWith(cmd); for (String l : log) { debug(l); if (l.contains("CompilerOracle") || l.contains("CompileCommand")) { debug("Found the suspected error line, no compiler blackholes."); return false; } } } // Step 2. See that CompilerOracle accepted the command explicitly { List<String> cmd = new ArrayList<>(); cmd.add(Utils.getCurrentJvm()); cmd.add("-XX:+UnlockExperimentalVMOptions"); cmd.add("-XX:CompileCommand=blackhole,some/fake/Class.method"); cmd.add("-version"); debug("Blackhole command acceptance test:"); Collection<String> log = Utils.runWith(cmd); for (String l : log) { debug(l); if (l.contains("CompilerOracle") || l.contains("CompileCommand")) { debug("Found the acceptance line, compiler blackholes are available."); return true; } } } // Err on the side of the caution: compiler blackholes are not available. debug("Compiler blackholes are not available."); return false; } private static void debug(String msg) { if (BLACKHOLE_MODE_DEBUG) { System.out.println(msg); } } public static void printHints(PrintStream out) { if (!compilerHintsSelect().isAuto()) { out.print("# Compiler hints: " + (compilerHintsEnabled() ? "enabled" : "disabled") + " (" + compilerHintsSelect().desc() + ")"); out.println(); } BlackholeMode mode = blackholeMode(); out.print("# Blackhole mode: " + mode.desc() + " (" + blackholeSelect().desc() + ")"); out.println(); } public static void printWarnings(PrintStream out) { if (blackholeMode() == BlackholeMode.COMPILER) { out.println("NOTE: Current JVM experimentally supports Compiler Blackholes, and they are in use. Please exercise"); out.println("extra caution when trusting the results, look into the generated code to check the benchmark still"); out.println("works, and factor in a small probability of new VM bugs. Additionally, while comparisons between"); out.println("different JVMs are already problematic, the performance difference caused by different Blackhole"); out.println("modes can be very significant. Please make sure you use the consistent Blackhole mode for comparisons."); out.println(); } } }
18,265
37.213389
140
java
jmh
jmh-master/jmh-core/src/main/java/org/openjdk/jmh/runner/Defaults.java
/* * Copyright (c) 2005, 2013, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package org.openjdk.jmh.runner; import org.openjdk.jmh.annotations.Mode; import org.openjdk.jmh.results.format.ResultFormatType; import org.openjdk.jmh.runner.options.TimeValue; import org.openjdk.jmh.runner.options.VerboseMode; import org.openjdk.jmh.runner.options.WarmupMode; import java.util.concurrent.TimeUnit; /** * JMH global defaults: these are used when no other values are available. */ public class Defaults { /** * Number of warmup iterations. */ public static final int WARMUP_ITERATIONS = 5; /** * Number of warmup iterations in {@link org.openjdk.jmh.annotations.Mode#SingleShotTime} mode. */ public static final int WARMUP_ITERATIONS_SINGLESHOT = 0; /** * The batch size in warmup mode. */ public static final int WARMUP_BATCHSIZE = 1; /** * The duration of warmup iterations. */ public static final TimeValue WARMUP_TIME = TimeValue.seconds(10); /** * Number of measurement iterations. */ public static final int MEASUREMENT_ITERATIONS = 5; /** * Number of measurement iterations in {@link org.openjdk.jmh.annotations.Mode#SingleShotTime} mode. */ public static final int MEASUREMENT_ITERATIONS_SINGLESHOT = 1; /** * The batch size in measurement mode. */ public static final int MEASUREMENT_BATCHSIZE = 1; /** * The duration of measurement iterations. */ public static final TimeValue MEASUREMENT_TIME = TimeValue.seconds(10); /** * Number of measurement threads. */ public static final int THREADS = 1; /** * Number of forks in which we measure the workload. */ public static final int MEASUREMENT_FORKS = 5; /** * Number of warmup forks we discard. */ public static final int WARMUP_FORKS = 0; /** * Should JMH fail on benchmark error? */ public static final boolean FAIL_ON_ERROR = false; /** * Should JMH synchronize iterations? */ public static final boolean SYNC_ITERATIONS = true; /** * Should JMH do GC between iterations? */ public static final boolean DO_GC = false; /** * The default {@link org.openjdk.jmh.results.format.ResultFormatType} to use. */ public static final ResultFormatType RESULT_FORMAT = ResultFormatType.CSV; /** * Default prefix of the result file. */ public static final String RESULT_FILE_PREFIX = "jmh-result"; /** * Default {@link org.openjdk.jmh.runner.options.WarmupMode}. */ public static final WarmupMode WARMUP_MODE = WarmupMode.INDI; /** * Default {@link org.openjdk.jmh.runner.options.VerboseMode}. */ public static final VerboseMode VERBOSITY = VerboseMode.NORMAL; /** * Default running mode. */ public static final Mode BENCHMARK_MODE = Mode.Throughput; /** * Default output time unit. */ public static final TimeUnit OUTPUT_TIMEUNIT = TimeUnit.SECONDS; /** * Default operations per invocation. */ public static final Integer OPS_PER_INVOCATION = 1; /** * Default timeout. */ public static final TimeValue TIMEOUT = TimeValue.minutes(10); /** * Default benchmarks to include. */ public static final String INCLUDE_BENCHMARKS = ".*"; }
4,552
28.185897
104
java
jmh
jmh-master/jmh-core/src/main/java/org/openjdk/jmh/runner/FailureAssistException.java
/* * Copyright (c) 2016, 2020, Red Hat Inc. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package org.openjdk.jmh.runner; /** * Thrown by worker threads when they detect other threads have failed. */ public class FailureAssistException extends RuntimeException { private static final long serialVersionUID = -7132741247248095175L; }
1,448
40.4
76
java
jmh
jmh-master/jmh-core/src/main/java/org/openjdk/jmh/runner/ForkedMain.java
/* * Copyright (c) 2005, 2013, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package org.openjdk.jmh.runner; import org.openjdk.jmh.runner.link.BinaryLinkClient; import org.openjdk.jmh.runner.options.Options; import java.io.IOException; import java.io.PrintStream; import java.util.Map; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicReference; /** * Main program entry point for forked JVM instance */ class ForkedMain { private static final AtomicBoolean hangupFuse = new AtomicBoolean(); private static final AtomicReference<BinaryLinkClient> linkRef = new AtomicReference<>(); private static volatile boolean gracefullyFinished; private static volatile Throwable exception; private static volatile PrintStream nakedErr; /** * Application main entry point * * @param argv Command line arguments */ public static void main(String[] argv) { if (argv.length != 2) { throw new IllegalArgumentException("Expected two arguments for forked VM"); } else { // capture nakedErr early, so that hangup/shutdown threads could use it nakedErr = System.err; // arm the hangup thread Runtime.getRuntime().addShutdownHook(new HangupThread()); // init the shutdown thread ShutdownTimeoutThread shutdownThread = new ShutdownTimeoutThread(); try { // This assumes the exact order of arguments: // 1) host name to back-connect // 2) host port to back-connect String hostName = argv[0]; int hostPort = Integer.parseInt(argv[1]); // establish the link to host VM and pull the options BinaryLinkClient link = new BinaryLinkClient(hostName, hostPort); linkRef.set(link); Options options = link.handshake(); // dump outputs into binary link System.setErr(link.getErrStream()); System.setOut(link.getOutStream()); // run! ForkedRunner runner = new ForkedRunner(options, link); runner.run(); gracefullyFinished = true; } catch (Throwable ex) { exception = ex; gracefullyFinished = false; } finally { // arm the shutdown timer shutdownThread.start(); } if (!gracefullyFinished) { System.exit(1); } } } /** * Report our latest status to the host VM, and say goodbye. */ static void hangup() { // hangup fires only once if (!hangupFuse.compareAndSet(false, true)) return; if (!gracefullyFinished) { Throwable ex = exception; if (ex == null) { ex = new IllegalStateException( "<failure: VM prematurely exited before JMH had finished with it, " + "explicit System.exit was called?>"); } String msg = ex.getMessage(); BinaryLinkClient link = linkRef.get(); if (link != null) { try { link.getOutputFormat().println(msg); link.pushException(new BenchmarkException(ex)); } catch (Exception e) { // last resort ex.printStackTrace(nakedErr); } } else { // last resort ex.printStackTrace(nakedErr); } } BinaryLinkClient link = linkRef.getAndSet(null); if (link != null) { try { link.close(); } catch (IOException e) { // swallow } } } /** * Hangup thread will detach us from the host VM properly, in three cases: * - normal shutdown * - shutdown with benchmark exception * - any System.exit call * * The need to intercept System.exit calls is the reason to register ourselves * as the shutdown hook. Additionally, this thread runs only when all non-daemon * threads are stopped, and therefore the stray user threads would be reported * by shutdown timeout thread over still alive binary link. */ private static class HangupThread extends Thread { @Override public void run() { hangup(); } } /** * Shutdown timeout thread will forcefully exit the VM in two cases: * - stray non-daemon thread prevents the VM from exiting * - all user threads have finished, but we are stuck in some shutdown hook or finalizer * * In all other "normal" cases, VM will exit before the timeout expires. */ private static class ShutdownTimeoutThread extends Thread { private static final int TIMEOUT = Integer.getInteger("jmh.shutdownTimeout", 30); private static final int TIMEOUT_STEP = Integer.getInteger("jmh.shutdownTimeout.step", 5); private static final String LINE_SEPARATOR = System.getProperty("line.separator"); public ShutdownTimeoutThread() { setName("JMH-Shutdown-Timeout"); setDaemon(true); } @Override public void run() { long start = System.nanoTime(); long waitMore; do { try { TimeUnit.SECONDS.sleep(TIMEOUT_STEP); } catch (InterruptedException e) { return; } waitMore = TimeUnit.SECONDS.toNanos(TIMEOUT) - (System.nanoTime() - start); String msg = getMessage(waitMore); BinaryLinkClient link = linkRef.get(); if (link != null) { link.getOutputFormat().println(msg); } else { // last resort nakedErr.println(msg); } } while (waitMore > 0); String msg = "<shutdown timeout of " + TIMEOUT + " seconds expired, forcing forked VM to exit>"; BinaryLinkClient link = linkRef.get(); if (link != null) { link.getOutputFormat().println(msg); } else { // last resort nakedErr.println(msg); } // aggressively try to hangup, and HALT hangup(); Runtime.getRuntime().halt(0); } private String getMessage(long waitMore) { StringBuilder sb = new StringBuilder(); sb.append("<JMH had finished, but forked VM did not exit, are there stray running threads? Waiting ") .append(TimeUnit.NANOSECONDS.toSeconds(waitMore)).append(" seconds more...>"); sb.append(LINE_SEPARATOR); sb.append(LINE_SEPARATOR); sb.append("Non-finished threads:"); sb.append(LINE_SEPARATOR); sb.append(LINE_SEPARATOR); for (Map.Entry<Thread, StackTraceElement[]> e : Thread.getAllStackTraces().entrySet()) { Thread thread = e.getKey(); StackTraceElement[] els = e.getValue(); if (thread.isDaemon()) continue; if (!thread.isAlive()) continue; sb.append(thread); sb.append(LINE_SEPARATOR); for (StackTraceElement el : els) { sb.append(" at "); sb.append(el); sb.append(LINE_SEPARATOR); } sb.append(LINE_SEPARATOR); } return sb.toString(); } } }
8,996
34.42126
113
java
jmh
jmh-master/jmh-core/src/main/java/org/openjdk/jmh/runner/ForkedRunner.java
/* * Copyright (c) 2005, 2020, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package org.openjdk.jmh.runner; import org.openjdk.jmh.results.BenchmarkResultMetaData; import org.openjdk.jmh.results.IterationResult; import org.openjdk.jmh.runner.link.BinaryLinkClient; import org.openjdk.jmh.runner.options.Options; import java.io.IOException; /** * Runner frontend class. Responsible for running micro benchmarks in forked JVM. */ class ForkedRunner extends BaseRunner { private final BinaryLinkClient link; public ForkedRunner(Options options, BinaryLinkClient link) { super(options, link.getOutputFormat()); this.link = link; } public void run() throws IOException, ClassNotFoundException { ActionPlan actionPlan = link.requestPlan(); try { IterationResultAcceptor acceptor = new IterationResultAcceptor() { @Override public void accept(IterationResult iterationData) { try { link.pushResults(iterationData); } catch (IOException e) { // link had probably failed throw new SavedIOException(e); } } @Override public void acceptMeta(BenchmarkResultMetaData md) { try { link.pushResultMetadata(md); } catch (IOException e) { // link had probably failed throw new SavedIOException(e); } } }; runBenchmarksForked(actionPlan, acceptor); } catch (BenchmarkException be) { link.pushException(be); } catch (SavedIOException ioe) { throw ioe.getCause(); } out.flush(); out.close(); } static class SavedIOException extends RuntimeException { private static final long serialVersionUID = -5807039363222713801L; private final IOException e; public SavedIOException(IOException e) { super(e); this.e = e; } public IOException getCause() { return e; } } }
3,399
33
81
java
jmh
jmh-master/jmh-core/src/main/java/org/openjdk/jmh/runner/InfraControl.java
/* * Copyright (c) 2005, 2013, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package org.openjdk.jmh.runner; import org.openjdk.jmh.infra.BenchmarkParams; import org.openjdk.jmh.infra.Control; import org.openjdk.jmh.infra.IterationParams; import org.openjdk.jmh.util.Utils; import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicInteger; /** * The InfraControl logic class. * This is the rendezvous class for benchmark handler and JMH. */ public class InfraControl extends InfraControlL4 { /** * Do the class hierarchy trick to evade false sharing, and check if it's working in runtime. * @see org.openjdk.jmh.infra.Blackhole description for the rationale */ static { Utils.check(InfraControl.class, "isDone", "isFailing"); Utils.check(InfraControl.class, "volatileSpoiler"); Utils.check(InfraControl.class, "preSetup", "preTearDown"); Utils.check(InfraControl.class, "firstIteration"); Utils.check(InfraControl.class, "lastIteration"); Utils.check(InfraControl.class, "shouldYield"); Utils.check(InfraControl.class, "warmupVisited", "warmdownVisited"); Utils.check(InfraControl.class, "warmupShouldWait", "warmdownShouldWait"); Utils.check(InfraControl.class, "warmupDone", "warmdownDone"); Utils.check(InfraControl.class, "benchmarkParams", "iterationParams"); Utils.check(InfraControl.class, "shouldSynchIterations", "threads"); } public InfraControl(BenchmarkParams benchmarkParams, IterationParams iterationParams, CountDownLatch preSetup, CountDownLatch preTearDown, boolean firstIteration, boolean lastIteration, boolean shouldYield, Control notifyControl) { super(benchmarkParams, iterationParams, preSetup, preTearDown, firstIteration, lastIteration, shouldYield, notifyControl); } /** * @return requested loop duration in milliseconds. */ public long getDuration() { return getDuration(TimeUnit.MILLISECONDS); } /** * @param unit timeunit to use * @return requested loop duration in the requested unit. */ public long getDuration(TimeUnit unit) { return iterationParams.getTime().convertTo(unit); } public void preSetup() { preSetup.countDown(); while (true) { try { preSetup.await(); return; } catch (InterruptedException e) { // Do not accept interrupts here. } } } public void preTearDown() { preTearDown.countDown(); while (true) { try { preTearDown.await(); return; } catch (InterruptedException e) { // Do not accept interrupts here. } } } public void preSetupForce() { preSetup.countDown(); } public void preTearDownForce() { preTearDown.countDown(); } public boolean isLastIteration() { return lastIteration; } public void announceDone() { isDone = true; notifyControl.stopMeasurement = true; } } abstract class InfraControlL0 { private int markerBegin; } abstract class InfraControlL1 extends InfraControlL0 { private boolean p001, p002, p003, p004, p005, p006, p007, p008; private boolean p011, p012, p013, p014, p015, p016, p017, p018; private boolean p021, p022, p023, p024, p025, p026, p027, p028; private boolean p031, p032, p033, p034, p035, p036, p037, p038; private boolean p041, p042, p043, p044, p045, p046, p047, p048; private boolean p051, p052, p053, p054, p055, p056, p057, p058; private boolean p061, p062, p063, p064, p065, p066, p067, p068; private boolean p071, p072, p073, p074, p075, p076, p077, p078; private boolean p101, p102, p103, p104, p105, p106, p107, p108; private boolean p111, p112, p113, p114, p115, p116, p117, p118; private boolean p121, p122, p123, p124, p125, p126, p127, p128; private boolean p131, p132, p133, p134, p135, p136, p137, p138; private boolean p141, p142, p143, p144, p145, p146, p147, p148; private boolean p151, p152, p153, p154, p155, p156, p157, p158; private boolean p161, p162, p163, p164, p165, p166, p167, p168; private boolean p171, p172, p173, p174, p175, p176, p177, p178; } abstract class InfraControlL2 extends InfraControlL1 { /** * Flag that checks for time expiration. * This is specifically the public field, so to spare one virtual call. */ public volatile boolean isDone; /** * Flag that checks for failure experienced by any measurement thread. * This is specifically the public field, so to spare one virtual call. */ public volatile boolean isFailing; public volatile boolean volatileSpoiler; public final CountDownLatch preSetup; public final CountDownLatch preTearDown; public final boolean firstIteration; public final boolean lastIteration; public final boolean shouldYield; public final AtomicInteger warmupVisited, warmdownVisited; public volatile boolean warmupShouldWait, warmdownShouldWait; public final CountDownLatch warmupDone, warmdownDone; public final BenchmarkParams benchmarkParams; public final IterationParams iterationParams; public final Control notifyControl; private final boolean shouldSynchIterations; private final int threads; public InfraControlL2(BenchmarkParams benchmarkParams, IterationParams iterationParams, CountDownLatch preSetup, CountDownLatch preTearDown, boolean firstIteration, boolean lastIteration, boolean shouldYield, Control notifyControl) { warmupVisited = new AtomicInteger(); warmdownVisited = new AtomicInteger(); warmupDone = new CountDownLatch(1); warmdownDone = new CountDownLatch(1); shouldSynchIterations = benchmarkParams.shouldSynchIterations(); threads = benchmarkParams.getThreads(); warmupShouldWait = shouldSynchIterations; warmdownShouldWait = shouldSynchIterations; this.notifyControl = notifyControl; this.preSetup = preSetup; this.preTearDown = preTearDown; this.firstIteration = firstIteration; this.lastIteration = lastIteration; this.shouldYield = shouldYield; this.benchmarkParams = benchmarkParams; this.iterationParams = iterationParams; } public void announceWarmupReady() { if (!shouldSynchIterations) return; int v = warmupVisited.incrementAndGet(); if (v == threads) { warmupShouldWait = false; warmupDone.countDown(); } if (v > threads) { throw new IllegalStateException("More threads than expected"); } } public void announceWarmdownReady() { if (!shouldSynchIterations) return; int v = warmdownVisited.incrementAndGet(); if (v == threads) { warmdownShouldWait = false; warmdownDone.countDown(); } if (v > threads) { throw new IllegalStateException("More threads than expected"); } } public void awaitWarmupReady() { if (warmupShouldWait) { try { warmupDone.await(); } catch (InterruptedException e) { // ignore } } } public void awaitWarmdownReady() { if (warmdownShouldWait) { try { warmdownDone.await(); } catch (InterruptedException e) { // ignore } } } public String getParam(String name) { String param = benchmarkParams.getParam(name); if (param == null) { throw new IllegalStateException("The value for the parameter \"" + name + "\" is not set."); } return param; } } abstract class InfraControlL3 extends InfraControlL2 { private boolean q001, q002, q003, q004, q005, q006, q007, q008; private boolean q011, q012, q013, q014, q015, q016, q017, q018; private boolean q021, q022, q023, q024, q025, q026, q027, q028; private boolean q031, q032, q033, q034, q035, q036, q037, q038; private boolean q041, q042, q043, q044, q045, q046, q047, q048; private boolean q051, q052, q053, q054, q055, q056, q057, q058; private boolean q061, q062, q063, q064, q065, q066, q067, q068; private boolean q071, q072, q073, q074, q075, q076, q077, q078; private boolean q101, q102, q103, q104, q105, q106, q107, q108; private boolean q111, q112, q113, q114, q115, q116, q117, q118; private boolean q121, q122, q123, q124, q125, q126, q127, q128; private boolean q131, q132, q133, q134, q135, q136, q137, q138; private boolean q141, q142, q143, q144, q145, q146, q147, q148; private boolean q151, q152, q153, q154, q155, q156, q157, q158; private boolean q161, q162, q163, q164, q165, q166, q167, q168; private boolean q171, q172, q173, q174, q175, q176, q177, q178; public InfraControlL3(BenchmarkParams benchmarkParams, IterationParams iterationParams, CountDownLatch preSetup, CountDownLatch preTearDown, boolean firstIteration, boolean lastIteration, boolean shouldYield, Control notifyControl) { super(benchmarkParams, iterationParams, preSetup, preTearDown, firstIteration, lastIteration, shouldYield, notifyControl); } } abstract class InfraControlL4 extends InfraControlL3 { private int markerEnd; public InfraControlL4(BenchmarkParams benchmarkParams, IterationParams iterationParams, CountDownLatch preSetup, CountDownLatch preTearDown, boolean firstIteration, boolean lastIteration, boolean shouldYield, Control notifyControl) { super(benchmarkParams, iterationParams, preSetup, preTearDown, firstIteration, lastIteration, shouldYield, notifyControl); } }
11,511
36.376623
130
java
jmh
jmh-master/jmh-core/src/main/java/org/openjdk/jmh/runner/IterationResultAcceptor.java
/* * Copyright (c) 2014, 2015, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package org.openjdk.jmh.runner; import org.openjdk.jmh.results.BenchmarkResultMetaData; import org.openjdk.jmh.results.IterationResult; interface IterationResultAcceptor { void accept(IterationResult iterationData); void acceptMeta(BenchmarkResultMetaData md); }
1,487
41.514286
79
java
jmh
jmh-master/jmh-core/src/main/java/org/openjdk/jmh/runner/IterationType.java
/* * Copyright (c) 2005, 2013, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package org.openjdk.jmh.runner; public enum IterationType { WARMUP, MEASUREMENT, }
1,305
41.129032
79
java
jmh
jmh-master/jmh-core/src/main/java/org/openjdk/jmh/runner/NoBenchmarksException.java
/* * Copyright (c) 2005, 2014, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package org.openjdk.jmh.runner; public class NoBenchmarksException extends RunnerException { private static final long serialVersionUID = 1446854343206595167L; public String toString() { return "No benchmarks to run; check the include/exclude regexps."; } }
1,494
41.714286
79
java
jmh
jmh-master/jmh-core/src/main/java/org/openjdk/jmh/runner/OutputFormatAdapter.java
/* * Copyright (c) 2014, 2014, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package org.openjdk.jmh.runner; import org.openjdk.jmh.runner.format.OutputFormat; import java.io.IOException; import java.io.OutputStream; class OutputFormatAdapter extends OutputStream { private final OutputFormat out; public OutputFormatAdapter(OutputFormat out) { this.out = out; } @Override public void write(int b) { out.write(b); } @Override public void write(byte[] b) throws IOException { out.write(b); } }
1,695
33.612245
79
java
jmh
jmh-master/jmh-core/src/main/java/org/openjdk/jmh/runner/PrintPropertiesMain.java
/* * Copyright (c) 2005, 2015, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package org.openjdk.jmh.runner; import org.openjdk.jmh.util.Utils; import java.io.BufferedOutputStream; import java.io.OutputStream; import java.nio.file.Files; import java.nio.file.Paths; /** * Main program entry point for exporting the system properties, used for detecting the VM version. */ class PrintPropertiesMain { /** * @param argv Command line arguments */ public static void main(String[] argv) throws Exception { if (argv.length != 1) { throw new IllegalArgumentException("Usage: java " + PrintPropertiesMain.class.getName() + " <xml-output-file>"); } try (OutputStream os = new BufferedOutputStream(Files.newOutputStream(Paths.get(argv[0])))) { Utils.getRecordedSystemProperties().storeToXML( os, "JMH properties export for target JVM", "UTF-8"); } } }
2,124
37.636364
124
java
jmh
jmh-master/jmh-core/src/main/java/org/openjdk/jmh/runner/ProfilersFailedException.java
/* * Copyright (c) 2005, 2015, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package org.openjdk.jmh.runner; import org.openjdk.jmh.profile.ProfilerException; public class ProfilersFailedException extends RunnerException { private static final long serialVersionUID = 1446854343206595167L; public ProfilersFailedException(ProfilerException e) { super("Profilers failed to initialize, exiting.", e); } }
1,562
42.416667
79
java
jmh
jmh-master/jmh-core/src/main/java/org/openjdk/jmh/runner/Runner.java
/* * Copyright (c) 2005, 2020, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package org.openjdk.jmh.runner; import org.openjdk.jmh.annotations.Mode; import org.openjdk.jmh.annotations.Threads; import org.openjdk.jmh.infra.BenchmarkParams; import org.openjdk.jmh.infra.IterationParams; import org.openjdk.jmh.profile.ExternalProfiler; import org.openjdk.jmh.profile.ProfilerException; import org.openjdk.jmh.profile.ProfilerFactory; import org.openjdk.jmh.results.*; import org.openjdk.jmh.results.format.ResultFormatFactory; import org.openjdk.jmh.runner.format.OutputFormat; import org.openjdk.jmh.runner.format.OutputFormatFactory; import org.openjdk.jmh.runner.link.BinaryLinkServer; import org.openjdk.jmh.runner.options.*; import org.openjdk.jmh.util.*; import org.openjdk.jmh.util.Optional; import java.io.*; import java.lang.management.ManagementFactory; import java.nio.channels.FileLock; import java.nio.channels.OverlappingFileLockException; import java.nio.file.Files; import java.nio.file.Path; import java.util.*; import java.util.concurrent.TimeUnit; import java.util.jar.*; import java.util.zip.*; /** * Runner executes JMH benchmarks. * * <p>This is the entry point for JMH Java API.</p> * * <p>{@link Runner} is not usually reusable. After you execute any method on the {@link Runner}, you should digest * the results, give up on current {@link Runner}, and instantiate another one. This class may be turned into * static class in future releases.</p> */ public class Runner extends BaseRunner { private static final int TAIL_LINES_ON_ERROR = Integer.getInteger("jmh.tailLines", 20); private static final String JMH_LOCK_FILE = System.getProperty("java.io.tmpdir") + "/jmh.lock"; private static final Boolean JMH_LOCK_IGNORE = Boolean.getBoolean("jmh.ignoreLock"); private final BenchmarkList list; private int cpuCount; /** * Create runner with the custom OutputFormat. * * @param options options to use * @param format OutputFormat to use */ public Runner(Options options, OutputFormat format) { super(options, format); this.list = BenchmarkList.defaultList(); } /** * Create Runner with the given options. * This method sets up the {@link org.openjdk.jmh.runner.format.OutputFormat} as * mandated by options. * @param options options to use. */ public Runner(Options options) { this(options, createOutputFormat(options)); } private static OutputFormat createOutputFormat(Options options) { // sadly required here as the check cannot be made before calling this method in constructor if (options == null) { throw new IllegalArgumentException("Options not allowed to be null."); } PrintStream out; if (options.getOutput().hasValue()) { try { out = new PrintStream(options.getOutput().get()); } catch (FileNotFoundException ex) { throw new IllegalStateException(ex); } } else { // Protect the System.out from accidental closing try { out = new UnCloseablePrintStream(System.out, Utils.guessConsoleEncoding()); } catch (UnsupportedEncodingException ex) { throw new IllegalStateException(ex); } } return OutputFormatFactory.createFormatInstance(out, options.verbosity().orElse(Defaults.VERBOSITY)); } /** * Print matching benchmarks into output. */ public void list() { Set<BenchmarkListEntry> benchmarks = list.find(out, options.getIncludes(), options.getExcludes()); out.println("Benchmarks: "); for (BenchmarkListEntry benchmark : benchmarks) { out.println(benchmark.getUsername()); } } /** * Print matching benchmarks with parameters into output. * @param options options to use. */ public void listWithParams(CommandLineOptions options) { Set<BenchmarkListEntry> benchmarks = list.find(out, options.getIncludes(), options.getExcludes()); out.println("Benchmarks: "); for (BenchmarkListEntry benchmark : benchmarks) { out.println(benchmark.getUsername()); Optional<Map<String, String[]>> params = benchmark.getParams(); if (params.hasValue()) { for (Map.Entry<String, String[]> e : params.get().entrySet()) { String param = e.getKey(); Collection<String> values = options.getParameter(param).orElse(Arrays.asList(e.getValue())); out.println(" param \"" + param + "\" = {" + Utils.join(values, ", ") + "}"); } } } } /** * Shortcut method for the single benchmark execution. * This method is handy when Options describe only the single benchmark to run. * * @return benchmark result * @throws RunnerException if more than one benchmark is found, or no results are returned */ public RunResult runSingle() throws RunnerException { Set<BenchmarkListEntry> benchmarks = list.find(out, options.getIncludes(), options.getExcludes()); if (benchmarks.size() == 1) { Collection<RunResult> values = run(); if (values.size() == 1) { return values.iterator().next(); } else { throw new RunnerException("No results returned"); } } else { if (benchmarks.size() > 1) { throw new RunnerException("More than single benchmark are matching the options: " + benchmarks); } else { throw new NoBenchmarksException(); } } } /** * Run benchmarks. * * @return map of benchmark results * @throws org.openjdk.jmh.runner.RunnerException if something goes wrong */ public Collection<RunResult> run() throws RunnerException { if (JMH_LOCK_IGNORE) { out.println("# WARNING: JMH lock is ignored by user request, make sure no other JMH instances are running"); return internalRun(); } final String tailMsg = " the JMH lock (" + JMH_LOCK_FILE + "), exiting. Use -Djmh.ignoreLock=true to forcefully continue."; File lockFile; try { lockFile = new File(JMH_LOCK_FILE); lockFile.createNewFile(); // Make sure the lock file is world-writeable, otherwise the lock file created by current // user would not work for any other user, always failing the run. lockFile.setWritable(true, false); } catch (IOException e) { throw new RunnerException("ERROR: Unable to create" + tailMsg, e); } try (RandomAccessFile raf = new RandomAccessFile(lockFile, "rw"); FileLock lock = raf.getChannel().tryLock()) { if (lock == null) { // Lock acquisition failed, pretend this was the overlap. throw new OverlappingFileLockException(); } return internalRun(); } catch (OverlappingFileLockException e) { throw new RunnerException("ERROR: Another JMH instance might be running. Unable to acquire" + tailMsg); } catch (IOException e) { throw new RunnerException("ERROR: Unexpected exception while trying to acquire" + tailMsg, e); } } private Collection<RunResult> internalRun() throws RunnerException { Set<String> profilerClasses = new HashSet<>(); ProfilersFailedException failedException = null; for (ProfilerConfig p : options.getProfilers()) { if (!profilerClasses.add(p.getKlass())) { throw new RunnerException("Cannot instantiate the same profiler more than once: " + p.getKlass()); } try { ProfilerFactory.getProfilerOrException(p); } catch (ProfilerException e) { if (failedException == null) { failedException = new ProfilersFailedException(e); } else { failedException.addSuppressed(e); } } } if (failedException != null) { throw failedException; } // If user requested the result file in one way or the other, touch the result file, // and prepare to write it out after the run. String resultFile = null; if (options.getResult().hasValue() || options.getResultFormat().hasValue()) { resultFile = options.getResult().orElse( Defaults.RESULT_FILE_PREFIX + "." + options.getResultFormat().orElse(Defaults.RESULT_FORMAT).toString().toLowerCase() ); try { FileUtils.touch(resultFile); } catch (IOException e) { throw new RunnerException("Can not touch the result file: " + resultFile); } } SortedSet<BenchmarkListEntry> benchmarks = list.find(out, options.getIncludes(), options.getExcludes()); if (benchmarks.isEmpty()) { out.flush(); out.close(); throw new NoBenchmarksException(); } // override the benchmark types; // this may yield new benchmark records if (!options.getBenchModes().isEmpty()) { List<BenchmarkListEntry> newBenchmarks = new ArrayList<>(); for (BenchmarkListEntry br : benchmarks) { for (Mode m : options.getBenchModes()) { newBenchmarks.add(br.cloneWith(m)); } } benchmarks.clear(); benchmarks.addAll(newBenchmarks); } // clone with all the modes { List<BenchmarkListEntry> newBenchmarks = new ArrayList<>(); for (BenchmarkListEntry br : benchmarks) { if (br.getMode() == Mode.All) { for (Mode mode : Mode.values()) { if (mode == Mode.All) continue; newBenchmarks.add(br.cloneWith(mode)); } } else { newBenchmarks.add(br); } } benchmarks.clear(); benchmarks.addAll(newBenchmarks); } // clone with all parameters { List<BenchmarkListEntry> newBenchmarks = new ArrayList<>(); for (BenchmarkListEntry br : benchmarks) { if (br.getParams().hasValue()) { for (WorkloadParams p : explodeAllParams(br)) { newBenchmarks.add(br.cloneWith(p)); } } else { newBenchmarks.add(br); } } benchmarks.clear(); benchmarks.addAll(newBenchmarks); } Collection<RunResult> results = runBenchmarks(benchmarks); // If user requested the result file, write it out. if (resultFile != null) { ResultFormatFactory.getInstance( options.getResultFormat().orElse(Defaults.RESULT_FORMAT), resultFile ).writeOut(results); out.println(""); out.println("Benchmark result is saved to " + resultFile); } out.flush(); out.close(); return results; } private List<ActionPlan> getActionPlans(Set<BenchmarkListEntry> benchmarks) { ActionPlan base = new ActionPlan(ActionType.FORKED); LinkedHashSet<BenchmarkListEntry> warmupBenches = new LinkedHashSet<>(); List<String> warmupMicrosRegexp = options.getWarmupIncludes(); if (warmupMicrosRegexp != null && !warmupMicrosRegexp.isEmpty()) { warmupBenches.addAll(list.find(out, warmupMicrosRegexp, Collections.<String>emptyList())); } if (options.getWarmupMode().orElse(Defaults.WARMUP_MODE).isBulk()) { warmupBenches.addAll(benchmarks); } for (BenchmarkListEntry wr : warmupBenches) { base.add(newAction(wr, ActionMode.WARMUP)); } ActionPlan embeddedPlan = new ActionPlan(ActionType.EMBEDDED); embeddedPlan.mixIn(base); boolean addEmbedded = false; List<ActionPlan> result = new ArrayList<>(); for (BenchmarkListEntry br : benchmarks) { BenchmarkParams params = newBenchmarkParams(br, ActionMode.UNDEF); if (params.getForks() <= 0) { if (options.getWarmupMode().orElse(Defaults.WARMUP_MODE).isIndi()) { embeddedPlan.add(newAction(br, ActionMode.WARMUP_MEASUREMENT)); } else { embeddedPlan.add(newAction(br, ActionMode.MEASUREMENT)); } addEmbedded = true; } if (params.getForks() > 0) { ActionPlan r = new ActionPlan(ActionType.FORKED); r.mixIn(base); if (options.getWarmupMode().orElse(Defaults.WARMUP_MODE).isIndi()) { r.add(newAction(br, ActionMode.WARMUP_MEASUREMENT)); } else { r.add(newAction(br, ActionMode.MEASUREMENT)); } result.add(r); } } if (addEmbedded) { result.add(embeddedPlan); } return result; } private Action newAction(BenchmarkListEntry br, ActionMode mode) { return new Action(newBenchmarkParams(br, mode), mode); } private BenchmarkParams newBenchmarkParams(BenchmarkListEntry benchmark, ActionMode mode) { int[] threadGroups = options.getThreadGroups().orElse(benchmark.getThreadGroups()); int threads = options.getThreads().orElse( benchmark.getThreads().orElse( Defaults.THREADS)); if (threads == Threads.MAX) { if (cpuCount == 0) { out.print("# Detecting actual CPU count: "); cpuCount = Utils.figureOutHotCPUs(); out.println(cpuCount + " detected"); } threads = cpuCount; } threads = Utils.roundUp(threads, Utils.sum(threadGroups)); boolean synchIterations = (benchmark.getMode() != Mode.SingleShotTime) && options.shouldSyncIterations().orElse(Defaults.SYNC_ITERATIONS); IterationParams measurement = mode.doMeasurement() ? new IterationParams( IterationType.MEASUREMENT, options.getMeasurementIterations().orElse( benchmark.getMeasurementIterations().orElse( (benchmark.getMode() == Mode.SingleShotTime) ? Defaults.MEASUREMENT_ITERATIONS_SINGLESHOT : Defaults.MEASUREMENT_ITERATIONS )), options.getMeasurementTime().orElse( benchmark.getMeasurementTime().orElse( (benchmark.getMode() == Mode.SingleShotTime) ? TimeValue.NONE : Defaults.MEASUREMENT_TIME )), options.getMeasurementBatchSize().orElse( benchmark.getMeasurementBatchSize().orElse( Defaults.MEASUREMENT_BATCHSIZE ) ) ) : new IterationParams(IterationType.MEASUREMENT, 0, TimeValue.NONE, 1); IterationParams warmup = mode.doWarmup() ? new IterationParams( IterationType.WARMUP, options.getWarmupIterations().orElse( benchmark.getWarmupIterations().orElse( (benchmark.getMode() == Mode.SingleShotTime) ? Defaults.WARMUP_ITERATIONS_SINGLESHOT : Defaults.WARMUP_ITERATIONS )), options.getWarmupTime().orElse( benchmark.getWarmupTime().orElse( (benchmark.getMode() == Mode.SingleShotTime) ? TimeValue.NONE : Defaults.WARMUP_TIME )), options.getWarmupBatchSize().orElse( benchmark.getWarmupBatchSize().orElse( Defaults.WARMUP_BATCHSIZE ) ) ) : new IterationParams(IterationType.WARMUP, 0, TimeValue.NONE, 1); int forks = options.getForkCount().orElse( benchmark.getForks().orElse( Defaults.MEASUREMENT_FORKS)); int warmupForks = options.getWarmupForkCount().orElse( benchmark.getWarmupForks().orElse( Defaults.WARMUP_FORKS)); TimeUnit timeUnit = options.getTimeUnit().orElse( benchmark.getTimeUnit().orElse( Defaults.OUTPUT_TIMEUNIT)); int opsPerInvocation = options.getOperationsPerInvocation().orElse( benchmark.getOperationsPerInvocation().orElse( Defaults.OPS_PER_INVOCATION)); String jvm = options.getJvm().orElse( benchmark.getJvm().orElse(Utils.getCurrentJvm())); Properties targetProperties; if (jvm.equals(Utils.getCurrentJvm())) { targetProperties = Utils.getRecordedSystemProperties(); } else { targetProperties = Utils.readPropertiesFromCommand(getPrintPropertiesCommand(jvm)); } Collection<String> jvmArgs = new ArrayList<>(); jvmArgs.addAll(options.getJvmArgsPrepend().orElse( benchmark.getJvmArgsPrepend().orElse(Collections.<String>emptyList()))); // We want to be extra lazy when accessing ManagementFactory, because security manager // may prevent us doing so. jvmArgs.addAll(options.getJvmArgs() .orElseGet(() -> benchmark.getJvmArgs() .orElseGet(() -> ManagementFactory.getRuntimeMXBean().getInputArguments()) )); jvmArgs.addAll(options.getJvmArgsAppend().orElse( benchmark.getJvmArgsAppend().orElse(Collections.<String>emptyList()))); TimeValue timeout = options.getTimeout().orElse( benchmark.getTimeout().orElse(Defaults.TIMEOUT)); String jdkVersion = targetProperties.getProperty("java.version"); String vmVersion = targetProperties.getProperty("java.vm.version"); String vmName = targetProperties.getProperty("java.vm.name"); return new BenchmarkParams(benchmark.getUsername(), benchmark.generatedTarget(), synchIterations, threads, threadGroups, benchmark.getThreadGroupLabels().orElse(Collections.<String>emptyList()), forks, warmupForks, warmup, measurement, benchmark.getMode(), benchmark.getWorkloadParams(), timeUnit, opsPerInvocation, jvm, jvmArgs, jdkVersion, vmName, vmVersion, Version.getPlainVersion(), timeout); } private List<WorkloadParams> explodeAllParams(BenchmarkListEntry br) throws RunnerException { Map<String, String[]> benchParams = br.getParams().orElse(Collections.<String, String[]>emptyMap()); List<WorkloadParams> ps = new ArrayList<>(); for (Map.Entry<String, String[]> e : benchParams.entrySet()) { String k = e.getKey(); String[] vals = e.getValue(); Collection<String> values = options.getParameter(k).orElse(Arrays.asList(vals)); if (values.isEmpty()) { throw new RunnerException("Benchmark \"" + br.getUsername() + "\" defines the parameter \"" + k + "\", but no default values.\n" + "Define the default values within the annotation, or provide the parameter values at runtime."); } if (ps.isEmpty()) { int idx = 0; for (String v : values) { WorkloadParams al = new WorkloadParams(); al.put(k, v, idx); ps.add(al); idx++; } } else { List<WorkloadParams> newPs = new ArrayList<>(); for (WorkloadParams p : ps) { int idx = 0; for (String v : values) { WorkloadParams al = p.copy(); al.put(k, v, idx); newPs.add(al); idx++; } } ps = newPs; } } return ps; } private Collection<RunResult> runBenchmarks(SortedSet<BenchmarkListEntry> benchmarks) throws RunnerException { out.startRun(); Multimap<BenchmarkParams, BenchmarkResult> results = new TreeMultimap<>(); List<ActionPlan> plan = getActionPlans(benchmarks); etaBeforeBenchmarks(plan); try { for (ActionPlan r : plan) { Multimap<BenchmarkParams, BenchmarkResult> res; switch (r.getType()) { case EMBEDDED: res = runBenchmarksEmbedded(r); break; case FORKED: res = runSeparate(r); break; default: throw new IllegalStateException("Unknown action plan type: " + r.getType()); } for (BenchmarkParams br : res.keys()) { results.putAll(br, res.get(br)); } } etaAfterBenchmarks(); SortedSet<RunResult> runResults = mergeRunResults(results); out.endRun(runResults); return runResults; } catch (BenchmarkException be) { throw new RunnerException("Benchmark caught the exception", be); } } private SortedSet<RunResult> mergeRunResults(Multimap<BenchmarkParams, BenchmarkResult> results) { SortedSet<RunResult> result = new TreeSet<>(RunResult.DEFAULT_SORT_COMPARATOR); for (BenchmarkParams key : results.keys()) { result.add(new RunResult(key, results.get(key))); } return result; } private Multimap<BenchmarkParams, BenchmarkResult> runSeparate(ActionPlan actionPlan) { Multimap<BenchmarkParams, BenchmarkResult> results = new HashMultimap<>(); if (actionPlan.getMeasurementActions().size() != 1) { throw new IllegalStateException("Expect only single benchmark in the action plan, but was " + actionPlan.getMeasurementActions().size()); } BinaryLinkServer server = null; try { server = new BinaryLinkServer(options, out); server.setPlan(actionPlan); BenchmarkParams params = actionPlan.getMeasurementActions().get(0).getParams(); List<ExternalProfiler> profilers = ProfilerFactory.getSupportedExternal(options.getProfilers()); boolean printOut = true; boolean printErr = true; for (ExternalProfiler prof : profilers) { printOut &= prof.allowPrintOut(); printErr &= prof.allowPrintErr(); } List<ExternalProfiler> profilersRev = new ArrayList<>(profilers); Collections.reverse(profilersRev); boolean forcePrint = options.verbosity().orElse(Defaults.VERBOSITY).equalsOrHigherThan(VerboseMode.EXTRA); printOut = forcePrint || printOut; printErr = forcePrint || printErr; out.startBenchmark(params); out.println(""); int forkCount = params.getForks(); int warmupForkCount = params.getWarmupForks(); int totalForks = warmupForkCount + forkCount; for (int i = 0; i < totalForks; i++) { boolean warmupFork = (i < warmupForkCount); List<String> forkedString = getForkedMainCommand(params, profilers, server.getHost(), server.getPort()); etaBeforeBenchmark(); if (warmupFork) { out.verbosePrintln("Warmup forking using command: " + forkedString); out.println("# Warmup Fork: " + (i + 1) + " of " + warmupForkCount); } else { out.verbosePrintln("Forking using command: " + forkedString); out.println("# Fork: " + (i + 1 - warmupForkCount) + " of " + forkCount); } TempFile stdErr = FileUtils.weakTempFile("stderr"); TempFile stdOut = FileUtils.weakTempFile("stdout"); if (!profilers.isEmpty()) { out.print("# Preparing profilers: "); for (ExternalProfiler profiler : profilers) { out.print(profiler.getClass().getSimpleName() + " "); profiler.beforeTrial(params); } out.println(""); List<String> consumed = new ArrayList<>(); if (!printOut) consumed.add("stdout"); if (!printErr) consumed.add("stderr"); if (!consumed.isEmpty()) { out.println("# Profilers consume " + Utils.join(consumed, " and ") + " from target VM, use -v " + VerboseMode.EXTRA + " to copy to console"); } } long startTime = System.currentTimeMillis(); List<IterationResult> result = doFork(server, forkedString, stdOut.file(), stdErr.file(), printOut, printErr); if (!result.isEmpty()) { long pid = server.getClientPid(); BenchmarkResultMetaData md = server.getMetadata(); if (md != null) { md.adjustStart(startTime); } BenchmarkResult br = new BenchmarkResult(params, result, md); if (!profilersRev.isEmpty()) { out.print("# Processing profiler results: "); for (ExternalProfiler profiler : profilersRev) { out.print(profiler.getClass().getSimpleName() + " "); for (Result profR : profiler.afterTrial(br, pid, stdOut.file(), stdErr.file())) { br.addBenchmarkResult(profR); } } out.println(""); } if (!warmupFork) { results.put(params, br); } } etaAfterBenchmark(params); out.println(""); // we know these are not needed anymore, proactively delete stdOut.delete(); stdErr.delete(); } out.endBenchmark(new RunResult(params, results.get(params)).getAggregatedResult()); } catch (IOException e) { results.clear(); throw new BenchmarkException(e); } catch (BenchmarkException e) { results.clear(); if (options.shouldFailOnError().orElse(Defaults.FAIL_ON_ERROR)) { out.println("Benchmark had encountered error, and fail on error was requested"); throw e; } } finally { if (server != null) { server.terminate(); } FileUtils.purgeTemps(); } return results; } private List<IterationResult> doFork(BinaryLinkServer reader, List<String> commandString, File stdOut, File stdErr, boolean printOut, boolean printErr) { try (FileOutputStream fosErr = new FileOutputStream(stdErr); FileOutputStream fosOut = new FileOutputStream(stdOut)) { ProcessBuilder pb = new ProcessBuilder(commandString); Process p = pb.start(); // drain streams, else we might lock up InputStreamDrainer errDrainer = new InputStreamDrainer(p.getErrorStream(), fosErr); InputStreamDrainer outDrainer = new InputStreamDrainer(p.getInputStream(), fosOut); if (printErr) { errDrainer.addOutputStream(new OutputFormatAdapter(out)); } if (printOut) { outDrainer.addOutputStream(new OutputFormatAdapter(out)); } errDrainer.start(); outDrainer.start(); int ecode = p.waitFor(); errDrainer.join(); outDrainer.join(); // need to wait for all pending messages to be processed // before starting the next benchmark reader.waitFinish(); if (ecode != 0) { out.println("<forked VM failed with exit code " + ecode + ">"); out.println("<stdout last='" + TAIL_LINES_ON_ERROR + " lines'>"); for (String l : FileUtils.tail(stdOut, TAIL_LINES_ON_ERROR)) { out.println(l); } out.println("</stdout>"); out.println("<stderr last='" + TAIL_LINES_ON_ERROR + " lines'>"); for (String l : FileUtils.tail(stdErr, TAIL_LINES_ON_ERROR)) { out.println(l); } out.println("</stderr>"); out.println(""); } BenchmarkException exception = reader.getException(); if (exception == null) { if (ecode == 0) { return reader.getResults(); } else { throw new BenchmarkException(new IllegalStateException("Forked VM failed with exit code " + ecode)); } } else { throw exception; } } catch (IOException ex) { out.println("<failed to invoke the VM, caught IOException: " + ex.getMessage() + ">"); out.println(""); throw new BenchmarkException(ex); } catch (InterruptedException ex) { out.println("<host VM has been interrupted waiting for forked VM: " + ex.getMessage() + ">"); out.println(""); throw new BenchmarkException(ex); } } /** * @param host host VM host * @param port host VM port * @return */ List<String> getForkedMainCommand(BenchmarkParams benchmark, List<ExternalProfiler> profilers, String host, int port) { // Poll profilers for options List<String> javaInvokeOptions = new ArrayList<>(); List<String> javaOptions = new ArrayList<>(); for (ExternalProfiler prof : profilers) { javaInvokeOptions.addAll(prof.addJVMInvokeOptions(benchmark)); javaOptions.addAll(prof.addJVMOptions(benchmark)); } List<String> command = new ArrayList<>(); // prefix java invoke options, if any profiler wants it command.addAll(javaInvokeOptions); // use supplied jvm, if given command.add(benchmark.getJvm()); // use supplied jvm args, if given command.addAll(benchmark.getJvmArgs()); // add profiler JVM commands, if any profiler wants it command.addAll(javaOptions); // add any compiler oracle hints CompilerHints.addCompilerHints(command); // assemble final process command addClasspath(command); command.add(ForkedMain.class.getName()); // Forked VM assumes the exact order of arguments: // 1) host name to back-connect // 2) host port to back-connect command.add(host); command.add(String.valueOf(port)); return command; } private List<String> getPrintPropertiesCommand(String jvm) { List<String> command = new ArrayList<>(); // use supplied jvm, if given command.add(jvm); // assemble final process command addClasspath(command); command.add(PrintPropertiesMain.class.getName()); return command; } private void addClasspath(List<String> command) { command.add("-cp"); String cpProp = System.getProperty("java.class.path"); File tmpFile = null; String jvmargs = "" + options.getJvmArgs().orElse(Collections.<String>emptyList()) + options.getJvmArgsPrepend().orElse(Collections.<String>emptyList()) + options.getJvmArgsAppend().orElse(Collections.<String>emptyList()); // The second (creepy) test is for the cases when external plugins are not supplying // the options properly. Looking at you, JMH Gradle plugin. In this case, we explicitly // check if the option is provided by the user. if (Boolean.getBoolean("jmh.separateClasspathJAR") || jvmargs.contains("jmh.separateClasspathJAR=true")) { // Classpath can be too long and overflow the command line length. // Looking at you, Windows. // // The trick is to generate the JAR file with appropriate Class-Path manifest entry, // and link it. The complication is that Class-Path entry paths are specified relative // to JAR file loaded, which is probably somewhere in java.io.tmpdir, outside of current // directory. Therefore, we have to relativize the paths to all the JAR entries. try { tmpFile = FileUtils.tempFile("classpath.jar"); Path tmpFileDir = tmpFile.toPath().getParent(); StringBuilder sb = new StringBuilder(); for (String cp : cpProp.split(File.pathSeparator)) { Path cpPath = new File(cp).getAbsoluteFile().toPath(); if (!cpPath.getRoot().equals(tmpFileDir.getRoot())) { throw new IOException("Cannot relativize: " + cpPath + " and " + tmpFileDir + " have different roots."); } Path relPath = tmpFileDir.relativize(cpPath); if (!Files.isReadable(tmpFileDir.resolve(relPath))) { throw new IOException("Cannot read through the relativized path: " + relPath); } String rel = relPath.toString(); sb.append(rel.replace('\\', '/').replace(" ", "%20")); if (Files.isDirectory(cpPath)) { sb.append('/'); } sb.append(" "); } String classPath = sb.toString().trim(); Manifest manifest = new Manifest(); Attributes attrs = manifest.getMainAttributes(); attrs.put(Attributes.Name.MANIFEST_VERSION, "1.0"); attrs.putValue("Class-Path", classPath); try (JarOutputStream jos = new JarOutputStream(new FileOutputStream(tmpFile), manifest)) { jos.putNextEntry(new ZipEntry("META-INF/")); } out.verbosePrintln("Using separate classpath JAR: " + tmpFile); out.verbosePrintln(" Class-Path: " + classPath); } catch (IOException ex) { // Something is wrong in file generation, give up and fall-through to usual thing out.verbosePrintln("Caught IOException when building separate classpath JAR: " + ex.getMessage() + ", falling back to default -cp."); tmpFile = null; } } if (tmpFile != null) { if (Utils.isWindows()) { command.add("\"" + tmpFile.getAbsolutePath() + "\""); } else { command.add(tmpFile.getAbsolutePath()); } } else { if (Utils.isWindows()) { command.add('"' + cpProp + '"'); } else { command.add(cpProp); } } } }
37,762
39.736785
165
java
jmh
jmh-master/jmh-core/src/main/java/org/openjdk/jmh/runner/RunnerException.java
/* * Copyright (c) 2005, 2013, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package org.openjdk.jmh.runner; public class RunnerException extends Exception { private static final long serialVersionUID = 7366763183238649668L; public RunnerException(Throwable t) { super(t); } public RunnerException() { super(); } public RunnerException(String s) { super(s); } public RunnerException(String s, Throwable cause) { super(s, cause); } }
1,643
33.978723
79
java
jmh
jmh-master/jmh-core/src/main/java/org/openjdk/jmh/runner/VersionMain.java
/* * Copyright (c) 2005, 2015, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package org.openjdk.jmh.runner; import org.openjdk.jmh.util.Utils; /** * Main program entry point detecting the VM version. */ class VersionMain { /** * @param argv Command line arguments */ public static void main(String[] argv) { System.err.println(Utils.getCurrentJvmVersion()); } }
1,535
35.571429
79
java
jmh
jmh-master/jmh-core/src/main/java/org/openjdk/jmh/runner/WorkerThreadFactories.java
/* * Copyright (c) 2005, 2023, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package org.openjdk.jmh.runner; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.util.concurrent.Executors; import java.util.concurrent.ThreadFactory; import java.util.concurrent.atomic.AtomicInteger; class WorkerThreadFactories { static class PlatformThreadFactory implements ThreadFactory { private final AtomicInteger counter; private final String prefix; private final ThreadFactory factory; public PlatformThreadFactory(String prefix) { this.counter = new AtomicInteger(); this.prefix = prefix; this.factory = Executors.defaultThreadFactory(); } @Override public Thread newThread(Runnable r) { Thread thread = factory.newThread(r); thread.setName(prefix + "-jmh-worker-" + counter.incrementAndGet()); thread.setDaemon(true); return thread; } } static ThreadFactory platformWorkerFactory(String prefix) { return new PlatformThreadFactory(prefix); } static ThreadFactory virtualWorkerFactory(String prefix) { // This API is only available in JDK 21+. Use reflection to make the code compilable with lower JDKs. try { Method m = Class.forName("java.lang.Thread").getMethod("ofVirtual"); Object threadBuilder = m.invoke(null); Class<?> threadBuilderClazz = Class.forName("java.lang.Thread$Builder"); m = threadBuilderClazz.getMethod("name", String.class, long.class); m.invoke(threadBuilder, prefix + "-jmh-worker-", 1L); m = threadBuilderClazz.getMethod("factory"); return (ThreadFactory) m.invoke(threadBuilder); } catch (NoSuchMethodException | InvocationTargetException | IllegalAccessException | ClassNotFoundException | NullPointerException e) { throw new RuntimeException("Cannot instantiate VirtualThreadFactory", e); } } }
3,228
40.935065
109
java
jmh
jmh-master/jmh-core/src/main/java/org/openjdk/jmh/runner/WorkloadParams.java
/* * Copyright (c) 2005, 2014, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package org.openjdk.jmh.runner; import java.io.Serializable; import java.util.*; public class WorkloadParams implements Comparable<WorkloadParams>, Serializable { private static final long serialVersionUID = 780563934988950196L; private final SortedMap<String, Value> params; public WorkloadParams() { params = new TreeMap<>(); } private WorkloadParams(SortedMap<String, Value> params) { this(); this.params.putAll(params); } @Override public int compareTo(WorkloadParams o) { if (!params.keySet().equals(o.params.keySet())) { throw new IllegalStateException("Comparing actual params with different key sets."); } for (Map.Entry<String, Value> e : params.entrySet()) { int cr = e.getValue().compareTo(o.params.get(e.getKey())); if (cr != 0) { return cr; } } return 0; } public void put(String k, String v, int vOrder) { params.put(k, new Value(v, vOrder)); } public boolean containsKey(String name) { return params.containsKey(name); } public String get(String name) { Value value = params.get(name); if (value == null) { return null; } else { return value.value; } } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; WorkloadParams that = (WorkloadParams) o; return Objects.equals(params, that.params); } @Override public int hashCode() { return params != null ? params.hashCode() : 0; } @Override public String toString() { return params.toString(); } public WorkloadParams copy() { return new WorkloadParams(params); } public boolean isEmpty() { return params.isEmpty(); } public Collection<String> keys() { return params.keySet(); } private static class Value implements Comparable<Value>, Serializable { private static final long serialVersionUID = 8846779314306880977L; private final String value; private final int order; public Value(String value, int order) { this.value = value; this.order = order; } @Override public int compareTo(Value o) { return Integer.compare(order, o.order); } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Value value1 = (Value) o; return Objects.equals(value, value1.value); } @Override public int hashCode() { return value != null ? value.hashCode() : 0; } } }
4,111
28.371429
96
java