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/test/java/org/openjdk/jmh/util/TestUtil.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.util;
import org.junit.Assert;
import org.junit.Test;
import java.io.IOException;
import java.util.Arrays;
public class TestUtil {
@Test
public void testPID_Current() {
Assert.assertTrue(Utils.getPid() != 0);
}
@Test
public void testPID_Other() throws IOException, InterruptedException {
if (!Utils.isWindows()) {
ProcessBuilder pb = new ProcessBuilder().command("sleep", "1");
Process p = pb.start();
Assert.assertTrue(Utils.getPid(p) != 0);
p.waitFor();
}
}
@Test
public void testSplit() {
Assert.assertEquals(Arrays.asList("moo"), Utils.splitQuotedEscape("moo"));
Assert.assertEquals(Arrays.asList("moo", "bar"), Utils.splitQuotedEscape("moo bar"));
Assert.assertEquals(Arrays.asList("moo", "bar"), Utils.splitQuotedEscape("moo bar"));
Assert.assertEquals(Arrays.asList("moo", "bar", "baz"), Utils.splitQuotedEscape("moo bar baz"));
Assert.assertEquals(Arrays.asList("moo", "bar baz"), Utils.splitQuotedEscape("moo \"bar baz\""));
Assert.assertEquals(Arrays.asList("moo", "-Dopt=bar baz"), Utils.splitQuotedEscape("moo -Dopt=\"bar baz\""));
}
}
| 2,452 | 39.213115 | 118 | java |
jmh | jmh-master/jmh-core/src/test/java/org/openjdk/jmh/util/Util.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.util;
import org.junit.Assert;
import java.util.Arrays;
public class Util {
public static void assertHistogram(Statistics s, double[] vals, int[] expected) {
int[] actual = s.getHistogram(vals);
Assert.assertEquals(expected.length, actual.length);
Assert.assertTrue(
"Expected " + Arrays.toString(expected) +
", but got " + Arrays.toString(actual),
Arrays.equals(expected, actual));
}
}
| 1,717 | 38.953488 | 85 | java |
jmh | jmh-master/jmh-core/src/test/java/org/openjdk/jmh/util/lines/TestArmor.java | /*
* Copyright (c) 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.util.lines;
import org.junit.Assert;
import org.junit.Test;
import java.util.Random;
public class TestArmor {
@Test
public void simple() {
String[] srcs = new String[] {
"jmh",
"test"
};
for (String src : srcs) {
Assert.assertEquals(src, src, Armor.decode(Armor.encode(src)));
}
}
@Test
public void exhaustivePlaces() {
for (char c = 0; c < Character.MAX_VALUE; c++) {
testFour(c, (char)0, (char)0, (char)0);
testFour((char)0, c, (char)0, (char)0);
testFour((char)0, (char)0, c, (char)0);
testFour((char)0, (char)0, (char)0, c);
}
}
private void testFour(char c1, char c2, char c3, char c4) {
StringBuilder sb = new StringBuilder();
sb.append(c1);
sb.append(c2);
sb.append(c3);
sb.append(c4);
String src = sb.toString();
String dst = Armor.decode(Armor.encode(src));
Assert.assertEquals(src, src, dst);
}
@Test
public void random() {
Random r = new Random(1);
for (int c = 0; c < 100000; c++) {
for (int s = 0; s < 10; s++) {
testWith(r, s, 127);
testWith(r, s, 255);
testWith(r, s, Character.MAX_VALUE - 10);
}
}
}
private void testWith(Random r, int size, int maxChar) {
StringBuilder sb = new StringBuilder();
for (int s = 0; s < size; s++) {
sb.append((char)r.nextInt(maxChar));
}
String src = sb.toString();
String dst = Armor.decode(Armor.encode(src));
Assert.assertEquals(src, src, dst);
}
}
| 2,939 | 30.276596 | 76 | java |
jmh | jmh-master/jmh-core/src/test/java/org/openjdk/jmh/util/lines/TestLineTest.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.util.lines;
import org.junit.Assert;
import org.junit.Test;
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.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;
public class TestLineTest {
@Test
public void test() {
TestLineWriter writer = new TestLineWriter();
writer.putString("jmh");
writer.putString("test");
writer.putOptionalString(Optional.eitherOf("full-optional"));
writer.putOptionalString(Optional.<String>none());
writer.putOptionalInt(Optional.eitherOf(42));
writer.putOptionalInt(Optional.<Integer>none());
writer.putIntArray(new int[] {5, 3, 2});
writer.putOptionalTimeValue(Optional.eitherOf(TimeValue.milliseconds(14)));
writer.putOptionalTimeValue(Optional.<TimeValue>none());
writer.putOptionalTimeUnit(Optional.eitherOf(TimeUnit.HOURS));
writer.putOptionalTimeUnit(Optional.<TimeUnit>none());
writer.putOptionalStringCollection(Optional.<Collection<String>>eitherOf(Arrays.asList("foo", "bar", "baz")));
writer.putOptionalStringCollection(Optional.<Collection<String>>none());
HashMap<String, String[]> expectedMap = new HashMap<>();
expectedMap.put("key1", new String[] {"val1", "val2"});
expectedMap.put("key2", new String[] {"val3", "val4"});
expectedMap.put("key3", new String[] {"val5\r", "val6"});
expectedMap.put("key4", new String[] {"val7\rn", "val8\n"});
writer.putOptionalParamCollection(Optional.<Map<String,String[]>>eitherOf(expectedMap));
writer.putOptionalParamCollection(Optional.<Map<String,String[]>>none());
String s = writer.toString();
TestLineReader reader = new TestLineReader(s);
Assert.assertEquals("jmh", reader.nextString());
Assert.assertEquals("test", reader.nextString());
Assert.assertEquals("full-optional", reader.nextOptionalString().get());
Assert.assertEquals(false, reader.nextOptionalString().hasValue());
Assert.assertEquals(42, (int)reader.nextOptionalInt().get());
Assert.assertEquals(false, reader.nextOptionalInt().hasValue());
Assert.assertTrue(Arrays.equals(new int[] {5, 3, 2}, reader.nextIntArray()));
Assert.assertEquals(TimeValue.milliseconds(14), reader.nextOptionalTimeValue().get());
Assert.assertEquals(false, reader.nextOptionalTimeValue().hasValue());
Assert.assertEquals(TimeUnit.HOURS, reader.nextOptionalTimeUnit().get());
Assert.assertEquals(false, reader.nextOptionalTimeUnit().hasValue());
Assert.assertEquals(Arrays.asList("foo", "bar", "baz"), reader.nextOptionalStringCollection().get());
Assert.assertEquals(false, reader.nextOptionalStringCollection().hasValue());
Map<String, String[]> actualMap = reader.nextOptionalParamCollection().get();
Assert.assertEquals(expectedMap.size(), actualMap.size());
Assert.assertEquals(expectedMap.keySet(), actualMap.keySet());
for (String key : expectedMap.keySet()) {
String[] expectedVals = expectedMap.get(key);
String[] actualVals = actualMap.get(key);
Assert.assertTrue(Arrays.equals(expectedVals, actualVals));
}
}
}
| 4,710 | 42.220183 | 118 | java |
jmh | jmh-master/jmh-generator-annprocess/src/main/java/org/openjdk/jmh/generators/BenchmarkProcessor.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;
import org.openjdk.jmh.generators.annotations.APGeneratorDestinaton;
import org.openjdk.jmh.generators.annotations.APGeneratorSource;
import org.openjdk.jmh.generators.core.BenchmarkGenerator;
import org.openjdk.jmh.generators.core.GeneratorDestination;
import org.openjdk.jmh.generators.core.GeneratorSource;
import javax.annotation.processing.AbstractProcessor;
import javax.annotation.processing.RoundEnvironment;
import javax.annotation.processing.SupportedAnnotationTypes;
import javax.lang.model.SourceVersion;
import javax.lang.model.element.TypeElement;
import java.util.Set;
@SupportedAnnotationTypes("org.openjdk.jmh.annotations.*")
public class BenchmarkProcessor extends AbstractProcessor {
private final BenchmarkGenerator generator = new BenchmarkGenerator();
@Override
public SourceVersion getSupportedSourceVersion() {
// We may claim to support the latest version, since we are not using
// any version-specific extensions.
return SourceVersion.latest();
}
@Override
public boolean process(Set<? extends TypeElement> annotations, RoundEnvironment roundEnv) {
GeneratorSource source = new APGeneratorSource(roundEnv, processingEnv);
GeneratorDestination destination = new APGeneratorDestinaton(roundEnv, processingEnv);
if (!roundEnv.processingOver()) {
generator.generate(source, destination);
} else {
generator.complete(source, destination);
}
return true;
}
}
| 2,760 | 41.476923 | 95 | java |
jmh | jmh-master/jmh-generator-annprocess/src/main/java/org/openjdk/jmh/generators/annotations/APClassInfo.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.annotations;
import org.openjdk.jmh.generators.core.ClassInfo;
import org.openjdk.jmh.generators.core.FieldInfo;
import org.openjdk.jmh.generators.core.MethodInfo;
import javax.annotation.processing.ProcessingEnvironment;
import javax.lang.model.element.Element;
import javax.lang.model.element.ElementKind;
import javax.lang.model.element.ExecutableElement;
import javax.lang.model.element.Modifier;
import javax.lang.model.element.PackageElement;
import javax.lang.model.element.TypeElement;
import javax.lang.model.element.VariableElement;
import javax.lang.model.type.TypeKind;
import javax.lang.model.type.TypeMirror;
import javax.lang.model.util.ElementFilter;
import java.lang.annotation.Annotation;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
class APClassInfo extends APMetadataInfo implements ClassInfo {
private final TypeElement el;
private final boolean isSpecial;
private final TypeMirror mirror;
public APClassInfo(ProcessingEnvironment processEnv, TypeElement element) {
super(processEnv, element);
if (element == null) {
throw new IllegalArgumentException("element is null");
}
this.el = element;
this.isSpecial = false;
this.mirror = null;
}
public APClassInfo(ProcessingEnvironment processEnv, TypeMirror mirror) {
super(processEnv, processEnv.getTypeUtils().asElement(mirror));
this.mirror = mirror;
this.isSpecial = mirror.getKind() != TypeKind.DECLARED;
if (isSpecial) {
this.el = null;
} else {
Element element = processEnv.getTypeUtils().asElement(mirror);
this.el = (TypeElement) element;
}
}
@Override
public <T extends Annotation> T getAnnotation(Class<T> annClass) {
if (isSpecial) return null;
return el.getAnnotation(annClass);
}
@Override
public Collection<MethodInfo> getConstructors() {
if (isSpecial) return Collections.emptyList();
Collection<MethodInfo> mis = new ArrayList<>();
for (ExecutableElement e : ElementFilter.constructorsIn(el.getEnclosedElements())) {
mis.add(new APMethodInfo(processEnv, this, e));
}
return mis;
}
@Override
public String getName() {
if (isSpecial) return mirror.toString();
return el.getSimpleName().toString();
}
@Override
public String getQualifiedName() {
if (isSpecial) return mirror.toString();
return el.getQualifiedName().toString();
}
@Override
public Collection<FieldInfo> getFields() {
if (isSpecial) return Collections.emptyList();
List<FieldInfo> ls = new ArrayList<>();
for (VariableElement e : ElementFilter.fieldsIn(el.getEnclosedElements())) {
ls.add(new APFieldInfo(processEnv, e));
}
return ls;
}
@Override
public Collection<MethodInfo> getMethods() {
if (isSpecial) return Collections.emptyList();
Collection<MethodInfo> mis = new ArrayList<>();
for (ExecutableElement e : ElementFilter.methodsIn(el.getEnclosedElements())) {
mis.add(new APMethodInfo(processEnv, this, e));
}
return mis;
}
@Override
public String getPackageName() {
if (isSpecial) return "";
Element walk = el;
while (walk.getKind() != ElementKind.PACKAGE) {
walk = walk.getEnclosingElement();
}
return ((PackageElement)walk).getQualifiedName().toString();
}
@Override
public ClassInfo getSuperClass() {
if (isSpecial) return null;
TypeMirror superclass = el.getSuperclass();
if (superclass.getKind() == TypeKind.NONE) {
return null;
} else {
TypeElement element = (TypeElement) processEnv.getTypeUtils().asElement(superclass);
return new APClassInfo(processEnv, element);
}
}
@Override
public ClassInfo getDeclaringClass() {
if (isSpecial) return null;
Element enclosingElement = el.getEnclosingElement();
if (enclosingElement.getKind() == ElementKind.CLASS) {
return new APClassInfo(processEnv, (TypeElement) enclosingElement);
} else {
return null;
}
}
@Override
public boolean isAbstract() {
if (isSpecial) return false;
return el.getModifiers().contains(Modifier.ABSTRACT);
}
@Override
public boolean isPublic() {
if (isSpecial) return true;
return el.getModifiers().contains(Modifier.PUBLIC);
}
@Override
public boolean isStrictFP() {
if (isSpecial) return false;
return el.getModifiers().contains(Modifier.STRICTFP);
}
@Override
public boolean isFinal() {
if (isSpecial) return false;
return el.getModifiers().contains(Modifier.FINAL);
}
@Override
public boolean isInner() {
if (isSpecial) return false;
return (getDeclaringClass() != null) && !el.getModifiers().contains(Modifier.STATIC);
}
@Override
public boolean isEnum() {
if (isSpecial) return false;
return el.getKind() == ElementKind.ENUM;
}
@Override
public Collection<String> getEnumConstants() {
Collection<String> result = new ArrayList<>();
for (Element e : el.getEnclosedElements()) {
if (e.getKind() == ElementKind.ENUM_CONSTANT) {
result.add(e.getSimpleName().toString());
}
}
return result;
}
public String toString() {
return getQualifiedName();
}
}
| 6,960 | 32.30622 | 96 | java |
jmh | jmh-master/jmh-generator-annprocess/src/main/java/org/openjdk/jmh/generators/annotations/APFieldInfo.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.annotations;
import org.openjdk.jmh.generators.core.ClassInfo;
import org.openjdk.jmh.generators.core.FieldInfo;
import javax.annotation.processing.ProcessingEnvironment;
import javax.lang.model.element.Modifier;
import javax.lang.model.element.TypeElement;
import javax.lang.model.element.VariableElement;
import java.lang.annotation.Annotation;
class APFieldInfo extends APMetadataInfo implements FieldInfo {
private final VariableElement ve;
public APFieldInfo(ProcessingEnvironment processEnv, VariableElement ve) {
super(processEnv, ve);
if (ve == null) {
throw new IllegalArgumentException("element is null");
}
this.ve = ve;
}
@Override
public String getName() {
return ve.getSimpleName().toString();
}
@Override
public ClassInfo getType() {
return new APClassInfo(processEnv, ve.asType());
}
@Override
public boolean isPublic() {
return ve.getModifiers().contains(Modifier.PUBLIC);
}
@Override
public boolean isStatic() {
return ve.getModifiers().contains(Modifier.STATIC);
}
@Override
public boolean isFinal() {
return ve.getModifiers().contains(Modifier.FINAL);
}
@Override
public <T extends Annotation> T getAnnotation(Class<T> annClass) {
return ve.getAnnotation(annClass);
}
@Override
public ClassInfo getDeclaringClass() {
return new APClassInfo(processEnv, (TypeElement)ve.getEnclosingElement());
}
public String toString() {
return getType() + " " + getName();
}
}
| 2,854 | 31.816092 | 82 | java |
jmh | jmh-master/jmh-generator-annprocess/src/main/java/org/openjdk/jmh/generators/annotations/APGeneratorDestinaton.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.annotations;
import org.openjdk.jmh.generators.core.GeneratorDestination;
import org.openjdk.jmh.generators.core.MetadataInfo;
import org.openjdk.jmh.util.Utils;
import javax.annotation.processing.Filer;
import javax.annotation.processing.ProcessingEnvironment;
import javax.annotation.processing.RoundEnvironment;
import javax.lang.model.element.TypeElement;
import javax.tools.Diagnostic;
import javax.tools.StandardLocation;
import java.io.*;
public class APGeneratorDestinaton implements GeneratorDestination {
private final ProcessingEnvironment processingEnv;
public APGeneratorDestinaton(RoundEnvironment roundEnv, ProcessingEnvironment processingEnv) {
this.processingEnv = processingEnv;
}
@Override
public OutputStream newResource(String resourcePath) throws IOException {
return processingEnv.getFiler().createResource(StandardLocation.CLASS_OUTPUT, "", resourcePath).openOutputStream();
}
@Override
public InputStream getResource(String resourcePath) throws IOException {
return processingEnv.getFiler().getResource(StandardLocation.CLASS_OUTPUT, "", resourcePath).openInputStream();
}
@Override
public Writer newClass(String className, String originatingClassName) throws IOException {
Filer filer = processingEnv.getFiler();
if (originatingClassName != null) {
TypeElement originatingType = processingEnv.getElementUtils().getTypeElement(originatingClassName);
return filer.createSourceFile(className, originatingType).openWriter();
} else {
return filer.createSourceFile(className).openWriter();
}
}
@Override
public void printError(String message) {
processingEnv.getMessager().printMessage(Diagnostic.Kind.ERROR, message);
}
@Override
public void printError(String message, MetadataInfo element) {
processingEnv.getMessager().printMessage(Diagnostic.Kind.ERROR, message, ((APMetadataInfo)element).getElement());
}
@Override
public void printError(String message, Throwable throwable) {
printError(message + " " + Utils.throwableToString(throwable));
}
@Override
public void printWarning(String message) {
processingEnv.getMessager().printMessage(Diagnostic.Kind.WARNING, message);
}
@Override
public void printWarning(String message, MetadataInfo element) {
processingEnv.getMessager().printMessage(Diagnostic.Kind.WARNING, message, ((APMetadataInfo)element).getElement());
}
@Override
public void printWarning(String message, Throwable throwable) {
printWarning(message + " " + Utils.throwableToString(throwable));
}
@Override
public void printNote(String message) {
processingEnv.getMessager().printMessage(Diagnostic.Kind.NOTE, message);
}
}
| 4,105 | 38.864078 | 123 | java |
jmh | jmh-master/jmh-generator-annprocess/src/main/java/org/openjdk/jmh/generators/annotations/APGeneratorSource.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.annotations;
import org.openjdk.jmh.generators.core.ClassInfo;
import org.openjdk.jmh.generators.core.GeneratorSource;
import javax.annotation.processing.ProcessingEnvironment;
import javax.annotation.processing.RoundEnvironment;
import javax.lang.model.element.Element;
import javax.lang.model.element.ElementKind;
import javax.lang.model.element.TypeElement;
import javax.lang.model.util.ElementFilter;
import javax.tools.Diagnostic;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Comparator;
import java.util.List;
import java.util.TreeSet;
public class APGeneratorSource implements GeneratorSource {
private final RoundEnvironment roundEnv;
private final ProcessingEnvironment processingEnv;
private Collection<ClassInfo> classInfos;
public APGeneratorSource(RoundEnvironment roundEnv, ProcessingEnvironment processingEnv) {
this.roundEnv = roundEnv;
this.processingEnv = processingEnv;
}
@Override
public Collection<ClassInfo> getClasses() {
if (classInfos != null) {
return classInfos;
}
Collection<TypeElement> discoveredClasses = new TreeSet<>(Comparator.comparing(o -> o.getQualifiedName().toString()));
// Need to do a few rollovers to find all classes that have @Benchmark-annotated methods in their
// subclasses. This is mostly due to some of the nested classes not discoverable at once,
// when we need to discover the enclosing class first. With the potentially non-zero nesting
// depth, we need to do a few rounds. Hopefully we will just do a single stride in most
// cases.
for (Element e : roundEnv.getRootElements()) {
if (e.getKind() != ElementKind.CLASS) continue;
discoveredClasses.add((TypeElement) e);
}
int lastSize = 0;
while (discoveredClasses.size() > lastSize) {
lastSize = discoveredClasses.size();
List<TypeElement> newClasses = new ArrayList<>();
for (Element e : discoveredClasses) {
try {
TypeElement walk = (TypeElement) e;
do {
newClasses.addAll(ElementFilter.typesIn(walk.getEnclosedElements()));
}
while ((walk = (TypeElement) processingEnv.getTypeUtils().asElement(walk.getSuperclass())) != null);
} catch (Exception t) {
// Working around the javac bug:
// https://bugs.openjdk.java.net/browse/JDK-8071778
//
// JMH ignores these exceptions since they probably consider the classes that do not
// have any JMH-related annotations. We can do nothing better than to notify the user,
// and bail from traversing a current class.
if (t.getClass().getName().endsWith("CompletionFailure")) {
processingEnv.getMessager().printMessage(Diagnostic.Kind.MANDATORY_WARNING, "While traversing " + e + ", caught " + t);
} else {
throw new RuntimeException(t);
}
}
}
discoveredClasses.addAll(newClasses);
}
classInfos = convert(discoveredClasses);
return classInfos;
}
protected Collection<ClassInfo> convert(Collection<TypeElement> els) {
List<ClassInfo> list = new ArrayList<>();
for (TypeElement el : els) {
list.add(new APClassInfo(processingEnv, el));
}
return list;
}
@Override
public ClassInfo resolveClass(String className) {
return new APClassInfo(processingEnv, processingEnv.getElementUtils().getTypeElement(className));
}
}
| 5,069 | 41.605042 | 143 | java |
jmh | jmh-master/jmh-generator-annprocess/src/main/java/org/openjdk/jmh/generators/annotations/APMetadataInfo.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.annotations;
import javax.annotation.processing.ProcessingEnvironment;
import javax.lang.model.element.Element;
class APMetadataInfo {
protected final ProcessingEnvironment processEnv;
private final Element element;
public APMetadataInfo(ProcessingEnvironment processEnv, Element element) {
this.processEnv = processEnv;
this.element = element;
}
public Element getElement() {
return element;
}
}
| 1,698 | 37.613636 | 79 | java |
jmh | jmh-master/jmh-generator-annprocess/src/main/java/org/openjdk/jmh/generators/annotations/APMethodInfo.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.annotations;
import org.openjdk.jmh.generators.core.ClassInfo;
import org.openjdk.jmh.generators.core.MethodInfo;
import org.openjdk.jmh.generators.core.ParameterInfo;
import javax.annotation.processing.ProcessingEnvironment;
import javax.lang.model.element.ExecutableElement;
import javax.lang.model.element.Modifier;
import javax.lang.model.element.VariableElement;
import java.lang.annotation.Annotation;
import java.util.ArrayList;
import java.util.Collection;
class APMethodInfo extends APMetadataInfo implements MethodInfo {
private final ClassInfo ci;
private final ExecutableElement el;
public APMethodInfo(ProcessingEnvironment processEnv, ClassInfo ci, ExecutableElement el) {
super(processEnv, el);
if (ci == null) {
throw new IllegalArgumentException("ci is null");
}
if (el == null) {
throw new IllegalArgumentException("el is null");
}
this.ci = ci;
this.el = el;
}
@Override
public ClassInfo getDeclaringClass() {
return ci;
}
@Override
public String getName() {
return el.getSimpleName().toString();
}
@Override
public String getReturnType() {
return el.getReturnType().toString();
}
@Override
public Collection<ParameterInfo> getParameters() {
Collection<ParameterInfo> pis = new ArrayList<>();
for (VariableElement v : el.getParameters()) {
pis.add(new APParameterInfo(processEnv, v));
}
return pis;
}
@Override
public <T extends Annotation> T getAnnotation(Class<T> annClass) {
return el.getAnnotation(annClass);
}
@Override
public boolean isPublic() {
return el.getModifiers().contains(Modifier.PUBLIC);
}
@Override
public boolean isAbstract() {
return el.getModifiers().contains(Modifier.ABSTRACT);
}
@Override
public boolean isSynchronized() {
return el.getModifiers().contains(Modifier.SYNCHRONIZED);
}
@Override
public boolean isStrictFP() {
return el.getModifiers().contains(Modifier.STRICTFP);
}
@Override
public boolean isStatic() {
return el.getModifiers().contains(Modifier.STATIC);
}
@Override
public String getQualifiedName() {
return ci.getQualifiedName() + "." + el.toString();
}
@Override
public int compareTo(MethodInfo o) {
return getQualifiedName().compareTo(o.getQualifiedName());
}
public String toString() {
return getDeclaringClass() + " " + getName() ;
}
}
| 3,854 | 29.84 | 95 | java |
jmh | jmh-master/jmh-generator-annprocess/src/main/java/org/openjdk/jmh/generators/annotations/APParameterInfo.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.annotations;
import org.openjdk.jmh.generators.core.ClassInfo;
import org.openjdk.jmh.generators.core.ParameterInfo;
import javax.annotation.processing.ProcessingEnvironment;
import javax.lang.model.element.VariableElement;
class APParameterInfo extends APMetadataInfo implements ParameterInfo {
private final VariableElement ve;
public APParameterInfo(ProcessingEnvironment processEnv, VariableElement ve) {
super(processEnv, ve);
if (ve == null) {
throw new IllegalArgumentException("element is null");
}
this.ve = ve;
}
@Override
public ClassInfo getType() {
return new APClassInfo(processEnv, ve.asType());
}
public String toString() {
return getType() + " " + ve.getSimpleName();
}
}
| 2,035 | 37.415094 | 82 | java |
jmh | jmh-master/jmh-generator-asm/src/main/java/org/openjdk/jmh/generators/asm/ASMClassInfo.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.asm;
import org.objectweb.asm.AnnotationVisitor;
import org.objectweb.asm.ClassVisitor;
import org.objectweb.asm.FieldVisitor;
import org.objectweb.asm.MethodVisitor;
import org.objectweb.asm.Opcodes;
import org.objectweb.asm.Type;
import org.openjdk.jmh.generators.core.ClassInfo;
import org.openjdk.jmh.generators.core.FieldInfo;
import org.openjdk.jmh.generators.core.MethodInfo;
import java.lang.annotation.Annotation;
import java.lang.reflect.Proxy;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
class ASMClassInfo extends ClassVisitor implements ClassInfo {
private String idName;
private String packageName;
private String qualifiedName;
private String name;
private int access;
private final List<MethodInfo> methods;
private final List<MethodInfo> constructors;
private final List<FieldInfo> fields;
private final Map<String, AnnotationInvocationHandler> annotations = new HashMap<>();
private final ClassInfoRepo classInfos;
private String superName;
private String declaringClass;
private boolean isInner;
private String origQualifiedName;
public ASMClassInfo(ClassInfoRepo classInfos) {
super(Opcodes.ASM5);
this.classInfos = classInfos;
this.methods = new ArrayList<>();
this.constructors = new ArrayList<>();
this.fields = new ArrayList<>();
}
public String getIdName() {
return idName;
}
@Override
public void visit(int version, int access, String name, String signature, String superName, String[] interfaces) {
super.visit(version, access, name, signature, superName, interfaces);
this.superName = superName;
this.idName = name;
this.access = access;
this.qualifiedName = name.replace("/", ".");
int dotIndex = qualifiedName.lastIndexOf(".");
if (dotIndex != -1) {
packageName = qualifiedName.substring(0, dotIndex);
} else {
packageName = "";
}
this.origQualifiedName = qualifiedName;
this.qualifiedName = qualifiedName.replace('$', '.');
dotIndex = qualifiedName.lastIndexOf(".");
if (dotIndex != -1) {
this.name = qualifiedName.substring(dotIndex + 1);
} else {
this.name = qualifiedName;
}
}
@Override
public <T extends Annotation> T getAnnotation(Class<T> annClass) {
AnnotationInvocationHandler handler = annotations.get(annClass.getCanonicalName());
if (handler == null) {
return null;
} else {
return (T) Proxy.newProxyInstance(
Thread.currentThread().getContextClassLoader(),
new Class[]{annClass},
handler);
}
}
@Override
public AnnotationVisitor visitAnnotation(final String desc, boolean visible) {
String className = Type.getType(desc).getClassName();
AnnotationInvocationHandler annHandler = new AnnotationInvocationHandler(className, super.visitAnnotation(desc, visible));
annotations.put(className, annHandler);
return annHandler;
}
@Override
public FieldVisitor visitField(int access, String name, String desc, String signature, Object value) {
ClassInfo type = classInfos.get(Type.getType(desc).getClassName());
FieldVisitor fv = super.visitField(access, name, desc, signature, value);
ASMFieldInfo fi = new ASMFieldInfo(fv, this, access, name, type);
fields.add(fi);
return fi;
}
@Override
public MethodVisitor visitMethod(int access, final String methodName, String methodDesc, String signature, String[] exceptions) {
ASMMethodInfo mi = new ASMMethodInfo(super.visitMethod(access, methodName, methodDesc, signature, exceptions),
classInfos, this, access, methodName, methodDesc, signature);
if (methodName.equals("<init>")) {
constructors.add(mi);
} else {
methods.add(mi);
}
return mi;
}
@Override
public String getPackageName() {
return packageName;
}
@Override
public String getName() {
return name;
}
@Override
public String getQualifiedName() {
return qualifiedName;
}
@Override
public Collection<FieldInfo> getFields() {
return fields;
}
@Override
public Collection<MethodInfo> getConstructors() {
return constructors;
}
@Override
public Collection<MethodInfo> getMethods() {
return methods;
}
@Override
public ClassInfo getSuperClass() {
return classInfos.get(superName);
}
@Override
public void visitInnerClass(String name, String outerName, String innerName, int access) {
if (name.equals(idName)) {
declaringClass = outerName;
}
super.visitInnerClass(name, outerName, innerName, access);
}
@Override
public void visitOuterClass(String owner, String name, String desc) {
isInner = true;
}
@Override
public ClassInfo getDeclaringClass() {
if (declaringClass != null) {
return classInfos.get(declaringClass);
} else {
return null;
}
}
@Override
public boolean isAbstract() {
return (access & Opcodes.ACC_ABSTRACT) > 0;
}
@Override
public boolean isPublic() {
return (access & Opcodes.ACC_PUBLIC) > 0;
}
@Override
public boolean isStrictFP() {
return (access & Opcodes.ACC_STRICT) > 0;
}
@Override
public boolean isFinal() {
return (access & Opcodes.ACC_FINAL) > 0;
}
@Override
public boolean isInner() {
return isInner;
}
@Override
public boolean isEnum() {
return (access & Opcodes.ACC_ENUM) > 0;
}
@Override
public Collection<String> getEnumConstants() {
if (isEnum()) {
try {
Collection<String> res = new ArrayList<>();
for (Object cnst : Class.forName(origQualifiedName, false, Thread.currentThread().getContextClassLoader()).getEnumConstants()) {
res.add(((Enum<?>) cnst).name());
}
return res;
} catch (ClassNotFoundException e) {
throw new IllegalStateException("Can not find and instantiate enum: " + origQualifiedName);
}
} else {
return Collections.emptyList();
}
}
@Override
public String toString() {
return qualifiedName;
}
}
| 7,985 | 30.565217 | 144 | java |
jmh | jmh-master/jmh-generator-asm/src/main/java/org/openjdk/jmh/generators/asm/ASMFieldInfo.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.asm;
import org.objectweb.asm.AnnotationVisitor;
import org.objectweb.asm.FieldVisitor;
import org.objectweb.asm.Opcodes;
import org.objectweb.asm.Type;
import org.openjdk.jmh.generators.core.ClassInfo;
import org.openjdk.jmh.generators.core.FieldInfo;
import java.lang.annotation.Annotation;
import java.lang.reflect.Proxy;
import java.util.HashMap;
import java.util.Map;
class ASMFieldInfo extends FieldVisitor implements FieldInfo {
private final ClassInfo type;
private final ASMClassInfo declaringClass;
private final int access;
private final String name;
private final Map<String, AnnotationInvocationHandler> annotations;
public ASMFieldInfo(FieldVisitor fieldVisitor, ASMClassInfo declaringClass, int access, String name, ClassInfo type) {
super(Opcodes.ASM5, fieldVisitor);
this.declaringClass = declaringClass;
this.access = access;
this.name = name;
this.type = type;
this.annotations = new HashMap<>();
}
@Override
public String getName() {
return name;
}
@Override
public ClassInfo getType() {
return type;
}
@Override
public boolean isPublic() {
return (access & Opcodes.ACC_PUBLIC) > 0;
}
@Override
public boolean isStatic() {
return (access & Opcodes.ACC_STATIC) > 0;
}
@Override
public boolean isFinal() {
return (access & Opcodes.ACC_FINAL) > 0;
}
@Override
public <T extends Annotation> T getAnnotation(Class<T> annClass) {
AnnotationInvocationHandler handler = annotations.get(annClass.getCanonicalName());
if (handler == null) {
return null;
} else {
return (T) Proxy.newProxyInstance(
Thread.currentThread().getContextClassLoader(),
new Class[]{annClass},
handler);
}
}
@Override
public AnnotationVisitor visitAnnotation(final String desc, boolean visible) {
String className = Type.getType(desc).getClassName();
AnnotationInvocationHandler annHandler = new AnnotationInvocationHandler(className, super.visitAnnotation(desc, visible));
annotations.put(className, annHandler);
return annHandler;
}
@Override
public ClassInfo getDeclaringClass() {
return declaringClass;
}
@Override
public String toString() {
return declaringClass.getQualifiedName() + "." + name;
}
}
| 3,740 | 32.401786 | 130 | java |
jmh | jmh-master/jmh-generator-asm/src/main/java/org/openjdk/jmh/generators/asm/ASMGeneratorSource.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.asm;
import org.objectweb.asm.ClassReader;
import org.openjdk.jmh.generators.core.ClassInfo;
import org.openjdk.jmh.generators.core.GeneratorSource;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Collection;
public class ASMGeneratorSource implements GeneratorSource {
private final ClassInfoRepo classInfos;
public ASMGeneratorSource() {
this.classInfos = new ClassInfoRepo();
}
public void processClasses(Collection<File> classFiles) throws IOException {
for (File f : classFiles) {
processClass(f);
}
}
public void processClass(File classFile) throws IOException {
try (FileInputStream fis = new FileInputStream(classFile)){
processClass(fis);
}
}
public void processClass(InputStream stream) throws IOException {
final ASMClassInfo ci = new ASMClassInfo(classInfos);
ClassReader reader = new ClassReader(stream);
reader.accept(ci, 0);
classInfos.put(ci.getIdName(), ci);
}
@Override
public Collection<ClassInfo> getClasses() {
return classInfos.getInfos();
}
@Override
public ClassInfo resolveClass(String className) {
return classInfos.get(className);
}
}
| 2,572 | 33.306667 | 81 | java |
jmh | jmh-master/jmh-generator-asm/src/main/java/org/openjdk/jmh/generators/asm/ASMMethodInfo.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.asm;
import org.objectweb.asm.AnnotationVisitor;
import org.objectweb.asm.MethodVisitor;
import org.objectweb.asm.Opcodes;
import org.objectweb.asm.Type;
import org.openjdk.jmh.generators.core.ClassInfo;
import org.openjdk.jmh.generators.core.MethodInfo;
import org.openjdk.jmh.generators.core.ParameterInfo;
import java.lang.annotation.Annotation;
import java.lang.reflect.Proxy;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
class ASMMethodInfo extends MethodVisitor implements MethodInfo {
private final ASMClassInfo declaringClass;
private final Map<String, AnnotationInvocationHandler> annotations;
private final int access;
private final String name;
private final String returnType;
private final Type[] argumentTypes;
private final ClassInfoRepo repo;
public ASMMethodInfo(MethodVisitor methodVisitor, ClassInfoRepo repo, ASMClassInfo declaringClass, int access, String name, String desc, String signature) {
super(Opcodes.ASM5, methodVisitor);
this.declaringClass = declaringClass;
this.repo = repo;
this.access = access;
this.name = name;
this.returnType = Type.getReturnType(desc).getClassName();
this.annotations = new HashMap<>();
this.argumentTypes = Type.getArgumentTypes(desc);
}
@Override
public <T extends Annotation> T getAnnotation(Class<T> annClass) {
AnnotationInvocationHandler handler = annotations.get(annClass.getCanonicalName());
if (handler == null) {
return null;
} else {
return (T) Proxy.newProxyInstance(
Thread.currentThread().getContextClassLoader(),
new Class[]{annClass},
handler);
}
}
@Override
public AnnotationVisitor visitAnnotation(final String desc, boolean visible) {
String className = Type.getType(desc).getClassName();
AnnotationInvocationHandler annHandler = new AnnotationInvocationHandler(className, super.visitAnnotation(desc, visible));
annotations.put(className, annHandler);
return annHandler;
}
@Override
public ClassInfo getDeclaringClass() {
return declaringClass;
}
@Override
public String getName() {
return name;
}
@Override
public String getQualifiedName() {
return declaringClass.getQualifiedName() + "." + name;
}
@Override
public String getReturnType() {
return returnType;
}
@Override
public Collection<ParameterInfo> getParameters() {
Collection<ParameterInfo> result = new ArrayList<>();
for (Type t : argumentTypes) {
ClassInfo ci = repo.get(t.getClassName());
result.add(new ASMParameterInfo(ci));
}
return result;
}
@Override
public boolean isPublic() {
return (access & Opcodes.ACC_PUBLIC) > 0;
}
@Override
public boolean isAbstract() {
return (access & Opcodes.ACC_ABSTRACT) > 0;
}
@Override
public boolean isSynchronized() {
return (access & Opcodes.ACC_SYNCHRONIZED) > 0;
}
@Override
public boolean isStrictFP() {
return (access & Opcodes.ACC_STRICT) > 0;
}
@Override
public boolean isStatic() {
return (access & Opcodes.ACC_STATIC) > 0;
}
@Override
public int compareTo(MethodInfo o) {
return getQualifiedName().compareTo(o.getQualifiedName());
}
@Override
public String toString() {
return getQualifiedName() + "()";
}
}
| 4,884 | 31.566667 | 160 | java |
jmh | jmh-master/jmh-generator-asm/src/main/java/org/openjdk/jmh/generators/asm/ASMParameterInfo.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.asm;
import org.openjdk.jmh.generators.core.ClassInfo;
import org.openjdk.jmh.generators.core.ParameterInfo;
class ASMParameterInfo implements ParameterInfo {
private final ClassInfo ci;
public ASMParameterInfo(ClassInfo ci) {
this.ci = ci;
}
@Override
public ClassInfo getType() {
return ci;
}
}
| 1,590 | 36 | 79 | java |
jmh | jmh-master/jmh-generator-asm/src/main/java/org/openjdk/jmh/generators/asm/AnnotationInvocationHandler.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.asm;
import org.objectweb.asm.AnnotationVisitor;
import org.objectweb.asm.Opcodes;
import org.openjdk.jmh.util.HashMultimap;
import org.openjdk.jmh.util.Multimap;
import java.lang.reflect.Array;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.util.Collection;
import java.util.HashSet;
import java.util.Set;
class AnnotationInvocationHandler extends AnnotationVisitor implements InvocationHandler {
private final String className;
private final Multimap<String, Object> values;
public AnnotationInvocationHandler(String className, AnnotationVisitor annotationVisitor) {
super(Opcodes.ASM5, annotationVisitor);
this.className = className;
this.values = new HashMultimap<>();
}
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
String member = method.getName();
Class<?> returnType = method.getReturnType();
Class<?>[] paramTypes = method.getParameterTypes();
if (member.equals("equals") && paramTypes.length == 1 &&
paramTypes[0] == Object.class)
return equalsImpl(args[0]);
if (paramTypes.length != 0)
throw new AssertionError("Too many parameters for an annotation method");
switch (member) {
case "toString":
return toStringImpl();
case "hashCode":
return hashcodeImpl();
case "annotationType":
throw new IllegalStateException("annotationType is not implemented");
}
/*
Unfortunately, we can not pre-process these values when walking the annotation
with ASM, since we are oblivious of exact types. Try to match the observed values
right here, based on the method return type.
*/
Collection<Object> vs = values.get(member);
if (vs == null || vs.isEmpty()) {
return method.getDefaultValue();
}
if (!returnType.isArray()) {
Object res = peelSingle(vs);
if (returnType.isEnum()) {
return parseEnum(returnType, res);
}
// String will return as is; primitive will auto-box
return res;
} else {
Class<?> componentType = returnType.getComponentType();
if (componentType.isEnum()) {
// Dealing with Enum[]:
Object res = Array.newInstance(componentType, vs.size());
int c = 0;
for (Object v : vs) {
Array.set(res, c, parseEnum(componentType, v));
c++;
}
return res;
} else if (componentType.isAssignableFrom(String.class)) {
// Dealing with String[]:
return vs.toArray(new String[0]);
} else {
// "Dealing" with primitive array:
// We do not have any primitive-array-valued annotations yet, so we don't bother to implement this.
throw new IllegalStateException("Primitive arrays are not handled yet");
}
}
}
private Object peelSingle(Collection<Object> vs) {
Object res;
if (vs.size() == 1) {
res = vs.iterator().next();
} else {
throw new IllegalStateException("Expected to see a single value, but got " + vs.size());
}
return res;
}
private String toStringImpl() {
StringBuilder sb = new StringBuilder();
sb.append("@");
sb.append(className);
sb.append("(");
for (String k : values.keys()) {
sb.append(k);
sb.append(" = ");
sb.append(values.get(k));
sb.append(", ");
}
sb.append(")");
return sb.toString();
}
private Object parseEnum(Class<?> type, Object res) throws Exception {
if (res == null) {
throw new IllegalStateException("The argument is null");
}
if (!(res instanceof String)) {
throw new IllegalStateException("The argument is not String, but " + res.getClass());
}
Method m = type.getMethod("valueOf", String.class);
return m.invoke(null, res);
}
private int hashcodeImpl() {
int result = className.hashCode();
for (String k : values.keys()) {
result = 31 * result + k.hashCode();
}
return result;
}
private boolean equalsImpl(Object arg) {
AnnotationInvocationHandler other = asOneOfUs(arg);
if (other != null) {
if (!className.equals(other.className)) {
return false;
}
Set<String> keys = new HashSet<>();
keys.addAll(values.keys());
keys.addAll(other.values.keys());
for (String k : keys) {
Collection<Object> o1 = values.get(k);
Collection<Object> o2 = other.values.get(k);
if (o1 == null || o2 == null) {
return false;
}
if (o1.size() != o2.size()) {
return false;
}
if (!o1.containsAll(o2) || !o2.containsAll(o1)) {
return false;
}
}
return true;
} else {
throw new IllegalStateException("Expected to see only AnnotationInvocationHandler-backed annotations");
}
}
private AnnotationInvocationHandler asOneOfUs(Object o) {
if (Proxy.isProxyClass(o.getClass())) {
InvocationHandler handler = Proxy.getInvocationHandler(o);
if (handler instanceof AnnotationInvocationHandler)
return (AnnotationInvocationHandler) handler;
}
return null;
}
@Override
public void visit(String name, Object value) {
values.put(name, value);
super.visit(name, value);
}
@Override
public void visitEnum(String name, String desc, String value) {
values.put(name, value);
super.visitEnum(name, desc, value);
}
@Override
public AnnotationVisitor visitArray(final String name) {
return new AnnotationVisitor(Opcodes.ASM5, super.visitArray(name)) {
@Override
public void visitEnum(String n, String desc, String value) {
values.put(name, value);
super.visitEnum(n, desc, value);
}
@Override
public void visit(String n, Object value) {
values.put(name, value);
super.visit(n, value);
}
};
}
}
| 8,021 | 34.030568 | 115 | java |
jmh | jmh-master/jmh-generator-asm/src/main/java/org/openjdk/jmh/generators/asm/ClassInfoRepo.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.asm;
import org.openjdk.jmh.generators.core.ClassInfo;
import org.openjdk.jmh.generators.reflection.RFGeneratorSource;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
class ClassInfoRepo {
private final Map<String, ClassInfo> map = new HashMap<>();
public ClassInfo get(String desc) {
desc = desc.replace('/', '.');
ClassInfo info = map.get(desc);
if (info != null) {
return info;
}
if (desc.equals(boolean.class.getCanonicalName())) return RFGeneratorSource.resolveClass(boolean.class);
if (desc.equals(byte.class.getCanonicalName())) return RFGeneratorSource.resolveClass(byte.class);
if (desc.equals(char.class.getCanonicalName())) return RFGeneratorSource.resolveClass(char.class);
if (desc.equals(short.class.getCanonicalName())) return RFGeneratorSource.resolveClass(short.class);
if (desc.equals(int.class.getCanonicalName())) return RFGeneratorSource.resolveClass(int.class);
if (desc.equals(float.class.getCanonicalName())) return RFGeneratorSource.resolveClass(float.class);
if (desc.equals(long.class.getCanonicalName())) return RFGeneratorSource.resolveClass(long.class);
if (desc.equals(double.class.getCanonicalName())) return RFGeneratorSource.resolveClass(double.class);
if (desc.equals(boolean[].class.getCanonicalName())) return RFGeneratorSource.resolveClass(boolean[].class);
if (desc.equals(byte[].class.getCanonicalName())) return RFGeneratorSource.resolveClass(byte[].class);
if (desc.equals(char[].class.getCanonicalName())) return RFGeneratorSource.resolveClass(char[].class);
if (desc.equals(short[].class.getCanonicalName())) return RFGeneratorSource.resolveClass(short[].class);
if (desc.equals(int[].class.getCanonicalName())) return RFGeneratorSource.resolveClass(int[].class);
if (desc.equals(float[].class.getCanonicalName())) return RFGeneratorSource.resolveClass(float[].class);
if (desc.equals(long[].class.getCanonicalName())) return RFGeneratorSource.resolveClass(long[].class);
if (desc.equals(double[].class.getCanonicalName())) return RFGeneratorSource.resolveClass(double[].class);
if (desc.endsWith("[]")) {
desc = "[L" + desc.substring(0, desc.length() - 2) + ";";
}
try {
return RFGeneratorSource.resolveClass(Class.forName(desc, false, Thread.currentThread().getContextClassLoader()));
} catch (ClassNotFoundException e) {
throw new IllegalStateException("Unable to resolve class: " + desc);
}
}
public void put(String desc, ClassInfo info) {
desc = desc.replace('/', '.');
map.put(desc, info);
}
public Collection<ClassInfo> getInfos() {
return map.values();
}
}
| 4,149 | 49 | 126 | java |
jmh | jmh-master/jmh-generator-bytecode/src/main/java/org/openjdk/jmh/generators/bytecode/JmhBytecodeGenerator.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.bytecode;
import org.openjdk.jmh.generators.asm.ASMGeneratorSource;
import org.openjdk.jmh.generators.core.BenchmarkGenerator;
import org.openjdk.jmh.generators.core.FileSystemDestination;
import org.openjdk.jmh.generators.core.GeneratorSource;
import org.openjdk.jmh.generators.core.SourceError;
import org.openjdk.jmh.generators.reflection.RFGeneratorSource;
import org.openjdk.jmh.util.FileUtils;
import java.io.File;
import java.net.URL;
import java.net.URLClassLoader;
import java.util.Collection;
public class JmhBytecodeGenerator {
public static final String GENERATOR_TYPE_DEFAULT = "default";
public static final String GENERATOR_TYPE_ASM = "asm";
public static final String GENERATOR_TYPE_REFLECTION = "reflection";
public static final String DEFAULT_GENERATOR_TYPE = GENERATOR_TYPE_REFLECTION;
public static void main(String[] args) throws Exception {
if (args.length < 3 || args.length > 4) {
System.err.println("Usage: generator <compiled-bytecode-dir> <output-source-dir> <output-resource-dir> [generator-type]");
System.exit(1);
}
File compiledBytecodeDirectory = new File(args[0]);
File outputSourceDirectory = new File(args[1]);
File outputResourceDirectory = new File(args[2]);
String generatorType = DEFAULT_GENERATOR_TYPE;
if (args.length >= 4) {
if (!args[3].equalsIgnoreCase(GENERATOR_TYPE_DEFAULT)) {
generatorType = args[3];
}
}
// Include compiled bytecode on classpath, in case we need to
// resolve the cross-class dependencies
URLClassLoader amendedCL = new URLClassLoader(
new URL[]{compiledBytecodeDirectory.toURI().toURL()},
Thread.currentThread().getContextClassLoader());
Thread.currentThread().setContextClassLoader(amendedCL);
FileSystemDestination destination = new FileSystemDestination(outputResourceDirectory, outputSourceDirectory);
Collection<File> classes = FileUtils.getClasses(compiledBytecodeDirectory);
System.out.println("Processing " + classes.size() + " classes from " + compiledBytecodeDirectory + " with \"" + generatorType + "\" generator");
System.out.println("Writing out Java source to " + outputSourceDirectory + " and resources to " + outputResourceDirectory);
GeneratorSource source = null;
if (generatorType.equalsIgnoreCase(GENERATOR_TYPE_ASM)) {
ASMGeneratorSource src = new ASMGeneratorSource();
src.processClasses(classes);
source = src;
} else if (generatorType.equalsIgnoreCase(GENERATOR_TYPE_REFLECTION)) {
RFGeneratorSource src = new RFGeneratorSource();
for (File f : classes) {
String name = f.getAbsolutePath().substring(compiledBytecodeDirectory.getAbsolutePath().length() + 1);
name = name.replaceAll("\\\\", ".");
name = name.replaceAll("/", ".");
if (name.endsWith(".class")) {
src.processClasses(Class.forName(name.substring(0, name.length() - 6), false, amendedCL));
}
}
source = src;
} else {
System.err.println("Unknown generator type: " + generatorType);
System.exit(1);
}
BenchmarkGenerator gen = new BenchmarkGenerator();
gen.generate(source, destination);
gen.complete(source, destination);
if (destination.hasErrors()) {
for (SourceError e : destination.getErrors()) {
System.err.println(e.toString() + "\n");
}
System.exit(1);
}
}
}
| 4,969 | 43.375 | 152 | java |
jmh | jmh-master/jmh-generator-reflection/src/main/java/org/openjdk/jmh/generators/reflection/RFClassInfo.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.reflection;
import org.openjdk.jmh.generators.core.ClassInfo;
import org.openjdk.jmh.generators.core.FieldInfo;
import org.openjdk.jmh.generators.core.MethodInfo;
import java.lang.annotation.Annotation;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.util.ArrayList;
import java.util.Collection;
class RFClassInfo implements ClassInfo {
private final Class<?> klass;
public RFClassInfo(Class<?> klass) {
this.klass = klass;
}
@Override
public String getPackageName() {
if (klass.getDeclaringClass() != null) {
return nameOf(klass.getDeclaringClass().getPackage());
} else {
return nameOf(klass.getPackage());
}
}
@Override
public String getName() {
String name = klass.getSimpleName();
if (name.contains("$")) {
return name.substring(name.lastIndexOf("$"));
} else {
return name;
}
}
@Override
public String getQualifiedName() {
String name = klass.getCanonicalName();
if (name == null) {
name = klass.getName();
}
if (name.contains("$")) {
return name.replace("$", ".");
} else {
return name;
}
}
@Override
public Collection<FieldInfo> getFields() {
Collection<FieldInfo> fis = new ArrayList<>();
for (Field f : klass.getDeclaredFields()) {
fis.add(new RFFieldInfo(this, f));
}
return fis;
}
@Override
public Collection<MethodInfo> getConstructors() {
Collection<MethodInfo> mis = new ArrayList<>();
for (Constructor m : klass.getDeclaredConstructors()) {
mis.add(new RFConstructorInfo(this, m));
}
return mis;
}
@Override
public Collection<MethodInfo> getMethods() {
Collection<MethodInfo> mis = new ArrayList<>();
for (Method m : klass.getDeclaredMethods()) {
mis.add(new RFMethodInfo(this, m));
}
return mis;
}
@Override
public ClassInfo getSuperClass() {
if (klass.getSuperclass() != null) {
return new RFClassInfo(klass.getSuperclass());
} else {
return null;
}
}
@Override
public ClassInfo getDeclaringClass() {
if (klass.getDeclaringClass() != null) {
return new RFClassInfo(klass.getDeclaringClass());
} else {
return null;
}
}
@Override
public <T extends Annotation> T getAnnotation(Class<T> annClass) {
return klass.getAnnotation(annClass);
}
@Override
public boolean isAbstract() {
return Modifier.isAbstract(klass.getModifiers());
}
@Override
public boolean isPublic() {
return Modifier.isPublic(klass.getModifiers());
}
@Override
public boolean isStrictFP() {
return Modifier.isStrict(klass.getModifiers());
}
@Override
public boolean isFinal() {
return Modifier.isFinal(klass.getModifiers());
}
@Override
public boolean isInner() {
// LOL, Reflection: http://mail.openjdk.java.net/pipermail/core-libs-dev/2014-February/025246.html
return klass.isAnonymousClass() ||
klass.isLocalClass() ||
(klass.isMemberClass() && !Modifier.isStatic(klass.getModifiers()));
}
@Override
public boolean isEnum() {
return klass.isEnum();
}
@Override
public Collection<String> getEnumConstants() {
Collection<String> res = new ArrayList<>();
for (Object cnst : klass.getEnumConstants()) {
res.add(((Enum<?>) cnst).name());
}
return res;
}
@Override
public String toString() {
return getQualifiedName();
}
private String nameOf(Package pack) {
return pack == null ? "" : pack.getName();
}
}
| 5,268 | 28.435754 | 106 | java |
jmh | jmh-master/jmh-generator-reflection/src/main/java/org/openjdk/jmh/generators/reflection/RFConstructorInfo.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.reflection;
import org.openjdk.jmh.generators.core.ClassInfo;
import org.openjdk.jmh.generators.core.MethodInfo;
import org.openjdk.jmh.generators.core.ParameterInfo;
import java.lang.annotation.Annotation;
import java.lang.reflect.Constructor;
import java.lang.reflect.Modifier;
import java.util.ArrayList;
import java.util.Collection;
class RFConstructorInfo implements MethodInfo {
private final RFClassInfo declaringClass;
private final Constructor m;
public RFConstructorInfo(RFClassInfo declaringClass, Constructor m) {
this.declaringClass = declaringClass;
this.m = m;
}
@Override
public ClassInfo getDeclaringClass() {
return declaringClass;
}
@Override
public String getName() {
return m.getName();
}
@Override
public String getQualifiedName() {
return declaringClass.getQualifiedName() + "." + m.getName();
}
@Override
public String getReturnType() {
throw new IllegalStateException("Asking the return type for constructor");
}
@Override
public Collection<ParameterInfo> getParameters() {
Collection<ParameterInfo> pis = new ArrayList<>();
for (Class<?> cl : m.getParameterTypes()) {
pis.add(new RFParameterInfo(cl));
}
return pis;
}
@Override
public <T extends Annotation> T getAnnotation(Class<T> annClass) {
throw new IllegalStateException("Asking annotations for constructor");
}
@Override
public boolean isPublic() {
return Modifier.isPublic(m.getModifiers());
}
@Override
public boolean isAbstract() {
return Modifier.isAbstract(m.getModifiers());
}
@Override
public boolean isSynchronized() {
return Modifier.isSynchronized(m.getModifiers());
}
@Override
public boolean isStrictFP() {
return Modifier.isStrict(m.getModifiers());
}
@Override
public boolean isStatic() {
return Modifier.isStatic(m.getModifiers());
}
@Override
public int compareTo(MethodInfo o) {
return getQualifiedName().compareTo(o.getQualifiedName());
}
}
| 3,415 | 29.774775 | 82 | java |
jmh | jmh-master/jmh-generator-reflection/src/main/java/org/openjdk/jmh/generators/reflection/RFFieldInfo.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.reflection;
import org.openjdk.jmh.generators.core.ClassInfo;
import org.openjdk.jmh.generators.core.FieldInfo;
import java.lang.annotation.Annotation;
import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
class RFFieldInfo implements FieldInfo {
private final ClassInfo declaringClass;
private final Field f;
public RFFieldInfo(ClassInfo declaringClass, Field f) {
this.declaringClass = declaringClass;
this.f = f;
}
@Override
public ClassInfo getDeclaringClass() {
return declaringClass;
}
@Override
public String getName() {
return f.getName();
}
@Override
public ClassInfo getType() {
return new RFClassInfo(f.getType());
}
@Override
public <T extends Annotation> T getAnnotation(Class<T> annClass) {
return f.getAnnotation(annClass);
}
@Override
public boolean isPublic() {
return Modifier.isPublic(f.getModifiers());
}
@Override
public boolean isStatic() {
return Modifier.isStatic(f.getModifiers());
}
@Override
public boolean isFinal() {
return Modifier.isFinal(f.getModifiers());
}
@Override
public String toString() {
return declaringClass.getQualifiedName() + "." + f.getName();
}
}
| 2,559 | 29.843373 | 79 | java |
jmh | jmh-master/jmh-generator-reflection/src/main/java/org/openjdk/jmh/generators/reflection/RFGeneratorSource.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.reflection;
import org.openjdk.jmh.generators.core.ClassInfo;
import org.openjdk.jmh.generators.core.GeneratorSource;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
public class RFGeneratorSource implements GeneratorSource {
private final Collection<Class> classes;
public RFGeneratorSource() {
this.classes = new ArrayList<>();
}
@Override
public Collection<ClassInfo> getClasses() {
Collection<ClassInfo> cis = new ArrayList<>();
for (Class c : classes) {
cis.add(new RFClassInfo(c));
}
return cis;
}
public static ClassInfo resolveClass(Class<?> klass) {
return new RFClassInfo(klass);
}
@Override
public ClassInfo resolveClass(String className) {
String desc = className.replace('/', '.');
try {
return resolveClass(Class.forName(desc, false, Thread.currentThread().getContextClassLoader()));
} catch (ClassNotFoundException e) {
throw new IllegalStateException("Unable to resolve class: " + desc);
}
}
public void processClasses(Class... cs) {
processClasses(Arrays.asList(cs));
}
public void processClasses(Collection<Class> cs) {
classes.addAll(cs);
}
}
| 2,546 | 33.890411 | 108 | java |
jmh | jmh-master/jmh-generator-reflection/src/main/java/org/openjdk/jmh/generators/reflection/RFMethodInfo.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.reflection;
import org.openjdk.jmh.generators.core.ClassInfo;
import org.openjdk.jmh.generators.core.MethodInfo;
import org.openjdk.jmh.generators.core.ParameterInfo;
import java.lang.annotation.Annotation;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.util.ArrayList;
import java.util.Collection;
class RFMethodInfo implements MethodInfo {
private final RFClassInfo declaringClass;
private final Method m;
public RFMethodInfo(RFClassInfo declaringClass, Method m) {
this.declaringClass = declaringClass;
this.m = m;
}
@Override
public ClassInfo getDeclaringClass() {
return declaringClass;
}
@Override
public String getName() {
return m.getName();
}
@Override
public String getQualifiedName() {
return declaringClass.getQualifiedName() + "." + m.getName();
}
@Override
public String getReturnType() {
return m.getReturnType().getCanonicalName();
}
@Override
public Collection<ParameterInfo> getParameters() {
Collection<ParameterInfo> pis = new ArrayList<>();
for (Class<?> cl : m.getParameterTypes()) {
pis.add(new RFParameterInfo(cl));
}
return pis;
}
@Override
public <T extends Annotation> T getAnnotation(Class<T> annClass) {
return m.getAnnotation(annClass);
}
@Override
public boolean isPublic() {
return Modifier.isPublic(m.getModifiers());
}
@Override
public boolean isAbstract() {
return Modifier.isAbstract(m.getModifiers());
}
@Override
public boolean isSynchronized() {
return Modifier.isSynchronized(m.getModifiers());
}
@Override
public boolean isStrictFP() {
return Modifier.isStrict(m.getModifiers());
}
@Override
public boolean isStatic() {
return Modifier.isStatic(m.getModifiers());
}
@Override
public int compareTo(MethodInfo o) {
return getQualifiedName().compareTo(o.getQualifiedName());
}
}
| 3,323 | 28.945946 | 79 | java |
jmh | jmh-master/jmh-generator-reflection/src/main/java/org/openjdk/jmh/generators/reflection/RFParameterInfo.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.reflection;
import org.openjdk.jmh.generators.core.ClassInfo;
import org.openjdk.jmh.generators.core.ParameterInfo;
class RFParameterInfo implements ParameterInfo {
private final Class<?> cl;
public RFParameterInfo(Class<?> cl) {
this.cl = cl;
}
@Override
public ClassInfo getType() {
return new RFClassInfo(cl);
}
}
| 1,609 | 37.333333 | 79 | java |
jmh | jmh-master/jmh-samples/src/main/java/org/openjdk/jmh/samples/JMHSample_01_HelloWorld.java | /*
* Copyright (c) 2014, Oracle America, Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* * Neither the name of Oracle nor the names of its contributors may be used
* to endorse or promote products derived from this software without
* specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
* THE POSSIBILITY OF SUCH DAMAGE.
*/
package org.openjdk.jmh.samples;
import org.openjdk.jmh.annotations.Benchmark;
import org.openjdk.jmh.runner.Runner;
import org.openjdk.jmh.runner.RunnerException;
import org.openjdk.jmh.runner.options.Options;
import org.openjdk.jmh.runner.options.OptionsBuilder;
public class JMHSample_01_HelloWorld {
/*
* This is our first benchmark method.
*
* JMH works as follows: users annotate the methods with @Benchmark, and
* then JMH produces the generated code to run this particular benchmark as
* reliably as possible. In general one might think about @Benchmark methods
* as the benchmark "payload", the things we want to measure. The
* surrounding infrastructure is provided by the harness itself.
*
* Read the Javadoc for @Benchmark annotation for complete semantics and
* restrictions. At this point we only note that the methods names are
* non-essential, and it only matters that the methods are marked with
* @Benchmark. You can have multiple benchmark methods within the same
* class.
*
* Note: if the benchmark method never finishes, then JMH run never finishes
* as well. If you throw an exception from the method body the JMH run ends
* abruptly for this benchmark and JMH will run the next benchmark down the
* list.
*
* Although this benchmark measures "nothing" it is a good showcase for the
* overheads the infrastructure bear on the code you measure in the method.
* There are no magical infrastructures which incur no overhead, and it is
* important to know what are the infra overheads you are dealing with. You
* might find this thought unfolded in future examples by having the
* "baseline" measurements to compare against.
*/
@Benchmark
public void wellHelloThere() {
// this method was intentionally left blank.
}
/*
* ============================== HOW TO RUN THIS TEST: ====================================
*
* You are expected to see the run with large number of iterations, and
* very large throughput numbers. You can see that as the estimate of the
* harness overheads per method call. In most of our measurements, it is
* down to several cycles per call.
*
* a) Via command-line:
* $ mvn clean install
* $ java -jar target/benchmarks.jar JMHSample_01
*
* JMH generates self-contained JARs, bundling JMH together with it.
* The runtime options for the JMH are available with "-h":
* $ java -jar target/benchmarks.jar -h
*
* b) Via the Java API:
* (see the JMH homepage for possible caveats when running from IDE:
* http://openjdk.java.net/projects/code-tools/jmh/)
*/
public static void main(String[] args) throws RunnerException {
Options opt = new OptionsBuilder()
.include(JMHSample_01_HelloWorld.class.getSimpleName())
.forks(1)
.build();
new Runner(opt).run();
}
}
| 4,625 | 43.057143 | 96 | java |
jmh | jmh-master/jmh-samples/src/main/java/org/openjdk/jmh/samples/JMHSample_02_BenchmarkModes.java | /*
* Copyright (c) 2014, Oracle America, Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* * Neither the name of Oracle nor the names of its contributors may be used
* to endorse or promote products derived from this software without
* specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
* THE POSSIBILITY OF SUCH DAMAGE.
*/
package org.openjdk.jmh.samples;
import org.openjdk.jmh.annotations.Benchmark;
import org.openjdk.jmh.annotations.BenchmarkMode;
import org.openjdk.jmh.annotations.Mode;
import org.openjdk.jmh.annotations.OutputTimeUnit;
import org.openjdk.jmh.runner.Runner;
import org.openjdk.jmh.runner.RunnerException;
import org.openjdk.jmh.runner.options.Options;
import org.openjdk.jmh.runner.options.OptionsBuilder;
import java.util.concurrent.TimeUnit;
public class JMHSample_02_BenchmarkModes {
/*
* JMH generates lots of synthetic code for the benchmarks for you during
* the benchmark compilation. JMH can measure the benchmark methods in lots
* of modes. Users may select the default benchmark mode with a special
* annotation, or select/override the mode via the runtime options.
*
* With this scenario, we start to measure something useful. Note that our
* payload code potentially throws exceptions, and we can just declare them
* to be thrown. If the code throws the actual exception, the benchmark
* execution will stop with an error.
*
* When you are puzzled with some particular behavior, it usually helps to
* look into the generated code. You might see the code is doing not
* something you intend it to do. Good experiments always follow up on the
* experimental setup, and cross-checking the generated code is an important
* part of that follow up.
*
* The generated code for this particular sample is somewhere at
* target/generated-sources/annotations/.../JMHSample_02_BenchmarkModes.java
*/
/*
* Mode.Throughput, as stated in its Javadoc, measures the raw throughput by
* continuously calling the benchmark method in a time-bound iteration, and
* counting how many times we executed the method.
*
* We are using the special annotation to select the units to measure in,
* although you can use the default.
*/
@Benchmark
@BenchmarkMode(Mode.Throughput)
@OutputTimeUnit(TimeUnit.SECONDS)
public void measureThroughput() throws InterruptedException {
TimeUnit.MILLISECONDS.sleep(100);
}
/*
* Mode.AverageTime measures the average execution time, and it does it
* in the way similar to Mode.Throughput.
*
* Some might say it is the reciprocal throughput, and it really is.
* There are workloads where measuring times is more convenient though.
*/
@Benchmark
@BenchmarkMode(Mode.AverageTime)
@OutputTimeUnit(TimeUnit.MICROSECONDS)
public void measureAvgTime() throws InterruptedException {
TimeUnit.MILLISECONDS.sleep(100);
}
/*
* Mode.SampleTime samples the execution time. With this mode, we are
* still running the method in a time-bound iteration, but instead of
* measuring the total time, we measure the time spent in *some* of
* the benchmark method calls.
*
* This allows us to infer the distributions, percentiles, etc.
*
* JMH also tries to auto-adjust sampling frequency: if the method
* is long enough, you will end up capturing all the samples.
*/
@Benchmark
@BenchmarkMode(Mode.SampleTime)
@OutputTimeUnit(TimeUnit.MICROSECONDS)
public void measureSamples() throws InterruptedException {
TimeUnit.MILLISECONDS.sleep(100);
}
/*
* Mode.SingleShotTime measures the single method invocation time. As the Javadoc
* suggests, we do only the single benchmark method invocation. The iteration
* time is meaningless in this mode: as soon as benchmark method stops, the
* iteration is over.
*
* This mode is useful to do cold startup tests, when you specifically
* do not want to call the benchmark method continuously.
*/
@Benchmark
@BenchmarkMode(Mode.SingleShotTime)
@OutputTimeUnit(TimeUnit.MICROSECONDS)
public void measureSingleShot() throws InterruptedException {
TimeUnit.MILLISECONDS.sleep(100);
}
/*
* We can also ask for multiple benchmark modes at once. All the tests
* above can be replaced with just a single test like this:
*/
@Benchmark
@BenchmarkMode({Mode.Throughput, Mode.AverageTime, Mode.SampleTime, Mode.SingleShotTime})
@OutputTimeUnit(TimeUnit.MICROSECONDS)
public void measureMultiple() throws InterruptedException {
TimeUnit.MILLISECONDS.sleep(100);
}
/*
* Or even...
*/
@Benchmark
@BenchmarkMode(Mode.All)
@OutputTimeUnit(TimeUnit.MICROSECONDS)
public void measureAll() throws InterruptedException {
TimeUnit.MILLISECONDS.sleep(100);
}
/*
* ============================== HOW TO RUN THIS TEST: ====================================
*
* You are expected to see the different run modes for the same benchmark.
* Note the units are different, scores are consistent with each other.
*
* You can run this test:
*
* a) Via the command line:
* $ mvn clean install
* $ java -jar target/benchmarks.jar JMHSample_02 -f 1
* (we requested a single fork; there are also other options, see -h)
*
* b) Via the Java API:
* (see the JMH homepage for possible caveats when running from IDE:
* http://openjdk.java.net/projects/code-tools/jmh/)
*/
public static void main(String[] args) throws RunnerException {
Options opt = new OptionsBuilder()
.include(JMHSample_02_BenchmarkModes.class.getSimpleName())
.forks(1)
.build();
new Runner(opt).run();
}
}
| 7,208 | 38.60989 | 96 | java |
jmh | jmh-master/jmh-samples/src/main/java/org/openjdk/jmh/samples/JMHSample_03_States.java | /*
* Copyright (c) 2014, Oracle America, Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* * Neither the name of Oracle nor the names of its contributors may be used
* to endorse or promote products derived from this software without
* specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
* THE POSSIBILITY OF SUCH DAMAGE.
*/
package org.openjdk.jmh.samples;
import org.openjdk.jmh.annotations.Benchmark;
import org.openjdk.jmh.annotations.Scope;
import org.openjdk.jmh.annotations.State;
import org.openjdk.jmh.runner.Runner;
import org.openjdk.jmh.runner.RunnerException;
import org.openjdk.jmh.runner.options.Options;
import org.openjdk.jmh.runner.options.OptionsBuilder;
public class JMHSample_03_States {
/*
* Most of the time, you need to maintain some state while the benchmark is
* running. Since JMH is heavily used to build concurrent benchmarks, we
* opted for an explicit notion of state-bearing objects.
*
* Below are two state objects. Their class names are not essential, it
* matters they are marked with @State. These objects will be instantiated
* on demand, and reused during the entire benchmark trial.
*
* The important property is that state is always instantiated by one of
* those benchmark threads which will then have the access to that state.
* That means you can initialize the fields as if you do that in worker
* threads (ThreadLocals are yours, etc).
*/
@State(Scope.Benchmark)
public static class BenchmarkState {
volatile double x = Math.PI;
}
@State(Scope.Thread)
public static class ThreadState {
volatile double x = Math.PI;
}
/*
* Benchmark methods can reference the states, and JMH will inject the
* appropriate states while calling these methods. You can have no states at
* all, or have only one state, or have multiple states referenced. This
* makes building multi-threaded benchmark a breeze.
*
* For this exercise, we have two methods.
*/
@Benchmark
public void measureUnshared(ThreadState state) {
// All benchmark threads will call in this method.
//
// However, since ThreadState is the Scope.Thread, each thread
// will have it's own copy of the state, and this benchmark
// will measure unshared case.
state.x++;
}
@Benchmark
public void measureShared(BenchmarkState state) {
// All benchmark threads will call in this method.
//
// Since BenchmarkState is the Scope.Benchmark, all threads
// will share the state instance, and we will end up measuring
// shared case.
state.x++;
}
/*
* ============================== HOW TO RUN THIS TEST: ====================================
*
* You are expected to see the drastic difference in shared and unshared cases,
* because you either contend for single memory location, or not. This effect
* is more articulated on large machines.
*
* You can run this test:
*
* a) Via the command line:
* $ mvn clean install
* $ java -jar target/benchmarks.jar JMHSample_03 -t 4 -f 1
* (we requested 4 threads, single fork; there are also other options, see -h)
*
* b) Via the Java API:
* (see the JMH homepage for possible caveats when running from IDE:
* http://openjdk.java.net/projects/code-tools/jmh/)
*/
public static void main(String[] args) throws RunnerException {
Options opt = new OptionsBuilder()
.include(JMHSample_03_States.class.getSimpleName())
.threads(4)
.forks(1)
.build();
new Runner(opt).run();
}
}
| 5,024 | 38.566929 | 96 | java |
jmh | jmh-master/jmh-samples/src/main/java/org/openjdk/jmh/samples/JMHSample_04_DefaultState.java | /*
* Copyright (c) 2014, Oracle America, Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* * Neither the name of Oracle nor the names of its contributors may be used
* to endorse or promote products derived from this software without
* specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
* THE POSSIBILITY OF SUCH DAMAGE.
*/
package org.openjdk.jmh.samples;
import org.openjdk.jmh.annotations.Benchmark;
import org.openjdk.jmh.annotations.Scope;
import org.openjdk.jmh.annotations.State;
import org.openjdk.jmh.runner.Runner;
import org.openjdk.jmh.runner.RunnerException;
import org.openjdk.jmh.runner.options.Options;
import org.openjdk.jmh.runner.options.OptionsBuilder;
/*
* Fortunately, in many cases you just need a single state object.
* In that case, we can mark the benchmark instance itself to be
* the @State. Then, we can reference its own fields as any
* Java program does.
*/
@State(Scope.Thread)
public class JMHSample_04_DefaultState {
double x = Math.PI;
@Benchmark
public void measure() {
x++;
}
/*
* ============================== HOW TO RUN THIS TEST: ====================================
*
* You can see the benchmark runs as usual.
*
* You can run this test:
*
* a) Via the command line:
* $ mvn clean install
* $ java -jar target/benchmarks.jar JMHSample_04 -f 1
* (we requested single fork; there are also other options, see -h)
*
* b) Via the Java API:
* (see the JMH homepage for possible caveats when running from IDE:
* http://openjdk.java.net/projects/code-tools/jmh/)
*/
public static void main(String[] args) throws RunnerException {
Options opt = new OptionsBuilder()
.include(JMHSample_04_DefaultState.class.getSimpleName())
.forks(1)
.build();
new Runner(opt).run();
}
}
| 3,164 | 36.235294 | 96 | java |
jmh | jmh-master/jmh-samples/src/main/java/org/openjdk/jmh/samples/JMHSample_05_StateFixtures.java | /*
* Copyright (c) 2014, Oracle America, Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* * Neither the name of Oracle nor the names of its contributors may be used
* to endorse or promote products derived from this software without
* specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
* THE POSSIBILITY OF SUCH DAMAGE.
*/
package org.openjdk.jmh.samples;
import org.openjdk.jmh.annotations.*;
import org.openjdk.jmh.runner.Runner;
import org.openjdk.jmh.runner.RunnerException;
import org.openjdk.jmh.runner.options.Options;
import org.openjdk.jmh.runner.options.OptionsBuilder;
@State(Scope.Thread)
public class JMHSample_05_StateFixtures {
double x;
/*
* Since @State objects are kept around during the lifetime of the
* benchmark, it helps to have the methods which do state housekeeping.
* These are usual fixture methods, you are probably familiar with them from
* JUnit and TestNG.
*
* Fixture methods make sense only on @State objects, and JMH will fail to
* compile the test otherwise.
*
* As with the State, fixture methods are only called by those benchmark
* threads which are using the state. That means you can operate in the
* thread-local context, and (not) use synchronization as if you are
* executing in the context of benchmark thread.
*
* Note: fixture methods can also work with static fields, although the
* semantics of these operations fall back out of State scope, and obey
* usual Java rules (i.e. one static field per class).
*/
/*
* Ok, let's prepare our benchmark:
*/
@Setup
public void prepare() {
x = Math.PI;
}
/*
* And, check the benchmark went fine afterwards:
*/
@TearDown
public void check() {
assert x > Math.PI : "Nothing changed?";
}
/*
* This method obviously does the right thing, incrementing the field x
* in the benchmark state. check() will never fail this way, because
* we are always guaranteed to have at least one benchmark call.
*/
@Benchmark
public void measureRight() {
x++;
}
/*
* This method, however, will fail the check(), because we deliberately
* have the "typo", and increment only the local variable. This should
* not pass the check, and JMH will fail the run.
*/
@Benchmark
public void measureWrong() {
double x = 0;
x++;
}
/*
* ============================== HOW TO RUN THIS TEST: ====================================
*
* You can see measureRight() yields the result, and measureWrong() fires
* the assert at the end of the run.
*
* You can run this test:
*
* a) Via the command line:
* $ mvn clean install
* $ java -ea -jar target/benchmarks.jar JMHSample_05 -f 1
* (we requested single fork; there are also other options, see -h)
*
* b) Via the Java API:
* (see the JMH homepage for possible caveats when running from IDE:
* http://openjdk.java.net/projects/code-tools/jmh/)
*/
public static void main(String[] args) throws RunnerException {
Options opt = new OptionsBuilder()
.include(JMHSample_05_StateFixtures.class.getSimpleName())
.forks(1)
.jvmArgs("-ea")
.build();
new Runner(opt).run();
}
}
| 4,682 | 34.210526 | 96 | java |
jmh | jmh-master/jmh-samples/src/main/java/org/openjdk/jmh/samples/JMHSample_06_FixtureLevel.java | /*
* Copyright (c) 2014, Oracle America, Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* * Neither the name of Oracle nor the names of its contributors may be used
* to endorse or promote products derived from this software without
* specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
* THE POSSIBILITY OF SUCH DAMAGE.
*/
package org.openjdk.jmh.samples;
import org.openjdk.jmh.annotations.*;
import org.openjdk.jmh.runner.Runner;
import org.openjdk.jmh.runner.RunnerException;
import org.openjdk.jmh.runner.options.Options;
import org.openjdk.jmh.runner.options.OptionsBuilder;
@State(Scope.Thread)
public class JMHSample_06_FixtureLevel {
double x;
/*
* Fixture methods have different levels to control when they should be run.
* There are at least three Levels available to the user. These are, from
* top to bottom:
*
* Level.Trial: before or after the entire benchmark run (the sequence of iterations)
* Level.Iteration: before or after the benchmark iteration (the sequence of invocations)
* Level.Invocation; before or after the benchmark method invocation (WARNING: read the Javadoc before using)
*
* Time spent in fixture methods does not count into the performance
* metrics, so you can use this to do some heavy-lifting.
*/
@TearDown(Level.Iteration)
public void check() {
assert x > Math.PI : "Nothing changed?";
}
@Benchmark
public void measureRight() {
x++;
}
@Benchmark
public void measureWrong() {
double x = 0;
x++;
}
/*
* ============================== HOW TO RUN THIS TEST: ====================================
*
* You can see measureRight() yields the result, and measureWrong() fires
* the assert at the end of first iteration! This will not generate the results
* for measureWrong(). You can also prevent JMH for proceeding further by
* requiring "fail on error".
*
* You can run this test:
*
* a) Via the command line:
* $ mvn clean install
* $ java -ea -jar target/benchmarks.jar JMHSample_06 -f 1
* (we requested single fork; there are also other options, see -h)
*
* You can optionally supply -foe to fail the complete run.
*
* b) Via the Java API:
* (see the JMH homepage for possible caveats when running from IDE:
* http://openjdk.java.net/projects/code-tools/jmh/)
*/
public static void main(String[] args) throws RunnerException {
Options opt = new OptionsBuilder()
.include(JMHSample_06_FixtureLevel.class.getSimpleName())
.forks(1)
.jvmArgs("-ea")
.shouldFailOnError(false) // switch to "true" to fail the complete run
.build();
new Runner(opt).run();
}
}
| 4,115 | 37.46729 | 113 | java |
jmh | jmh-master/jmh-samples/src/main/java/org/openjdk/jmh/samples/JMHSample_07_FixtureLevelInvocation.java | /*
* Copyright (c) 2014, Oracle America, Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* * Neither the name of Oracle nor the names of its contributors may be used
* to endorse or promote products derived from this software without
* specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
* THE POSSIBILITY OF SUCH DAMAGE.
*/
package org.openjdk.jmh.samples;
import org.openjdk.jmh.annotations.*;
import org.openjdk.jmh.runner.Runner;
import org.openjdk.jmh.runner.RunnerException;
import org.openjdk.jmh.runner.options.Options;
import org.openjdk.jmh.runner.options.OptionsBuilder;
import java.util.concurrent.*;
/**
* Fixtures have different Levels to control when they are about to run.
* Level.Invocation is useful sometimes to do some per-invocation work
* which should not count as payload (e.g. sleep for some time to emulate
* think time)
*/
@OutputTimeUnit(TimeUnit.MICROSECONDS)
public class JMHSample_07_FixtureLevelInvocation {
/*
* Fixtures have different Levels to control when they are about to run.
* Level.Invocation is useful sometimes to do some per-invocation work,
* which should not count as payload. PLEASE NOTE the timestamping and
* synchronization for Level.Invocation helpers might significantly offset
* the measurement, use with care. See Level.Invocation javadoc for further
* discussion.
*
* Consider this sample:
*/
/*
* This state handles the executor.
* Note we create and shutdown executor with Level.Trial, so
* it is kept around the same across all iterations.
*/
@State(Scope.Benchmark)
public static class NormalState {
ExecutorService service;
@Setup(Level.Trial)
public void up() {
service = Executors.newCachedThreadPool();
}
@TearDown(Level.Trial)
public void down() {
service.shutdown();
}
}
/*
* This is the *extension* of the basic state, which also
* has the Level.Invocation fixture method, sleeping for some time.
*/
public static class LaggingState extends NormalState {
public static final int SLEEP_TIME = Integer.getInteger("sleepTime", 10);
@Setup(Level.Invocation)
public void lag() throws InterruptedException {
TimeUnit.MILLISECONDS.sleep(SLEEP_TIME);
}
}
/*
* This allows us to formulate the task: measure the task turnaround in
* "hot" mode when we are not sleeping between the submits, and "cold" mode,
* when we are sleeping.
*/
@Benchmark
@BenchmarkMode(Mode.AverageTime)
public double measureHot(NormalState e, final Scratch s) throws ExecutionException, InterruptedException {
return e.service.submit(new Task(s)).get();
}
@Benchmark
@BenchmarkMode(Mode.AverageTime)
public double measureCold(LaggingState e, final Scratch s) throws ExecutionException, InterruptedException {
return e.service.submit(new Task(s)).get();
}
/*
* This is our scratch state which will handle the work.
*/
@State(Scope.Thread)
public static class Scratch {
private double p;
public double doWork() {
p = Math.log(p);
return p;
}
}
public static class Task implements Callable<Double> {
private Scratch s;
public Task(Scratch s) {
this.s = s;
}
@Override
public Double call() {
return s.doWork();
}
}
/*
* ============================== HOW TO RUN THIS TEST: ====================================
*
* You can see the cold scenario is running longer, because we pay for
* thread wakeups.
*
* You can run this test:
*
* a) Via the command line:
* $ mvn clean install
* $ java -jar target/benchmarks.jar JMHSample_07 -f 1
* (we requested single fork; there are also other options, see -h)
*
* b) Via the Java API:
* (see the JMH homepage for possible caveats when running from IDE:
* http://openjdk.java.net/projects/code-tools/jmh/)
*/
public static void main(String[] args) throws RunnerException {
Options opt = new OptionsBuilder()
.include(JMHSample_07_FixtureLevelInvocation.class.getSimpleName())
.forks(1)
.build();
new Runner(opt).run();
}
}
| 5,704 | 32.757396 | 112 | java |
jmh | jmh-master/jmh-samples/src/main/java/org/openjdk/jmh/samples/JMHSample_08_DeadCode.java | /*
* Copyright (c) 2014, Oracle America, Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* * Neither the name of Oracle nor the names of its contributors may be used
* to endorse or promote products derived from this software without
* specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
* THE POSSIBILITY OF SUCH DAMAGE.
*/
package org.openjdk.jmh.samples;
import org.openjdk.jmh.annotations.*;
import org.openjdk.jmh.runner.Runner;
import org.openjdk.jmh.runner.RunnerException;
import org.openjdk.jmh.runner.options.Options;
import org.openjdk.jmh.runner.options.OptionsBuilder;
import java.util.concurrent.TimeUnit;
@State(Scope.Thread)
@BenchmarkMode(Mode.AverageTime)
@OutputTimeUnit(TimeUnit.NANOSECONDS)
public class JMHSample_08_DeadCode {
/*
* The downfall of many benchmarks is Dead-Code Elimination (DCE): compilers
* are smart enough to deduce some computations are redundant and eliminate
* them completely. If the eliminated part was our benchmarked code, we are
* in trouble.
*
* Fortunately, JMH provides the essential infrastructure to fight this
* where appropriate: returning the result of the computation will ask JMH
* to deal with the result to limit dead-code elimination (returned results
* are implicitly consumed by Blackholes, see JMHSample_09_Blackholes).
*/
private double x = Math.PI;
private double compute(double d) {
for (int c = 0; c < 10; c++) {
d = d * d / Math.PI;
}
return d;
}
@Benchmark
public void baseline() {
// do nothing, this is a baseline
}
@Benchmark
public void measureWrong() {
// This is wrong: result is not used and the entire computation is optimized away.
compute(x);
}
@Benchmark
public double measureRight() {
// This is correct: the result is being used.
return compute(x);
}
/*
* ============================== HOW TO RUN THIS TEST: ====================================
*
* You can see the unrealistically fast calculation in with measureWrong(),
* while realistic measurement with measureRight().
*
* You can run this test:
*
* a) Via the command line:
* $ mvn clean install
* $ java -jar target/benchmarks.jar JMHSample_08 -f 1
* (we requested single fork; there are also other options, see -h)
*
* b) Via the Java API:
* (see the JMH homepage for possible caveats when running from IDE:
* http://openjdk.java.net/projects/code-tools/jmh/)
*/
public static void main(String[] args) throws RunnerException {
Options opt = new OptionsBuilder()
.include(JMHSample_08_DeadCode.class.getSimpleName())
.forks(1)
.build();
new Runner(opt).run();
}
}
| 4,122 | 35.8125 | 96 | java |
jmh | jmh-master/jmh-samples/src/main/java/org/openjdk/jmh/samples/JMHSample_09_Blackholes.java | /*
* Copyright (c) 2014, Oracle America, Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* * Neither the name of Oracle nor the names of its contributors may be used
* to endorse or promote products derived from this software without
* specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
* THE POSSIBILITY OF SUCH DAMAGE.
*/
package org.openjdk.jmh.samples;
import org.openjdk.jmh.annotations.*;
import org.openjdk.jmh.infra.Blackhole;
import org.openjdk.jmh.runner.Runner;
import org.openjdk.jmh.runner.RunnerException;
import org.openjdk.jmh.runner.options.Options;
import org.openjdk.jmh.runner.options.OptionsBuilder;
import java.util.concurrent.TimeUnit;
@BenchmarkMode(Mode.AverageTime)
@OutputTimeUnit(TimeUnit.NANOSECONDS)
@State(Scope.Thread)
public class JMHSample_09_Blackholes {
/*
* Should your benchmark require returning multiple results, you have to
* consider two options (detailed below).
*
* NOTE: If you are only producing a single result, it is more readable to
* use the implicit return, as in JMHSample_08_DeadCode. Do not make your benchmark
* code less readable with explicit Blackholes!
*/
double x1 = Math.PI;
double x2 = Math.PI * 2;
private double compute(double d) {
for (int c = 0; c < 10; c++) {
d = d * d / Math.PI;
}
return d;
}
/*
* Baseline measurement: how much a single compute() costs.
*/
@Benchmark
public double baseline() {
return compute(x1);
}
/*
* While the compute(x2) computation is intact, compute(x1)
* is redundant and optimized out.
*/
@Benchmark
public double measureWrong() {
compute(x1);
return compute(x2);
}
/*
* This demonstrates Option A:
*
* Merge multiple results into one and return it.
* This is OK when is computation is relatively heavyweight, and merging
* the results does not offset the results much.
*/
@Benchmark
public double measureRight_1() {
return compute(x1) + compute(x2);
}
/*
* This demonstrates Option B:
*
* Use explicit Blackhole objects, and sink the values there.
* (Background: Blackhole is just another @State object, bundled with JMH).
*/
@Benchmark
public void measureRight_2(Blackhole bh) {
bh.consume(compute(x1));
bh.consume(compute(x2));
}
/*
* ============================== HOW TO RUN THIS TEST: ====================================
*
* You will see measureWrong() running on-par with baseline().
* Both measureRight() are measuring twice the baseline, so the logs are intact.
*
* You can run this test:
*
* a) Via the command line:
* $ mvn clean install
* $ java -jar target/benchmarks.jar JMHSample_09 -f 1
* (we requested single fork; there are also other options, see -h)
*
* b) Via the Java API:
* (see the JMH homepage for possible caveats when running from IDE:
* http://openjdk.java.net/projects/code-tools/jmh/)
*/
public static void main(String[] args) throws RunnerException {
Options opt = new OptionsBuilder()
.include(JMHSample_09_Blackholes.class.getSimpleName())
.forks(1)
.build();
new Runner(opt).run();
}
}
| 4,647 | 31.964539 | 96 | java |
jmh | jmh-master/jmh-samples/src/main/java/org/openjdk/jmh/samples/JMHSample_10_ConstantFold.java | /*
* Copyright (c) 2014, Oracle America, Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* * Neither the name of Oracle nor the names of its contributors may be used
* to endorse or promote products derived from this software without
* specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
* THE POSSIBILITY OF SUCH DAMAGE.
*/
package org.openjdk.jmh.samples;
import org.openjdk.jmh.annotations.*;
import org.openjdk.jmh.runner.Runner;
import org.openjdk.jmh.runner.RunnerException;
import org.openjdk.jmh.runner.options.Options;
import org.openjdk.jmh.runner.options.OptionsBuilder;
import java.util.concurrent.TimeUnit;
@State(Scope.Thread)
@BenchmarkMode(Mode.AverageTime)
@OutputTimeUnit(TimeUnit.NANOSECONDS)
public class JMHSample_10_ConstantFold {
/*
* The flip side of dead-code elimination is constant-folding.
*
* If JVM realizes the result of the computation is the same no matter what,
* it can cleverly optimize it. In our case, that means we can move the
* computation outside of the internal JMH loop.
*
* This can be prevented by always reading the inputs from non-final
* instance fields of @State objects, computing the result based on those
* values, and follow the rules to prevent DCE.
*/
// IDEs will say "Oh, you can convert this field to local variable". Don't. Trust. Them.
// (While this is normally fine advice, it does not work in the context of measuring correctly.)
private double x = Math.PI;
// IDEs will probably also say "Look, it could be final". Don't. Trust. Them. Either.
// (While this is normally fine advice, it does not work in the context of measuring correctly.)
private final double wrongX = Math.PI;
private double compute(double d) {
for (int c = 0; c < 10; c++) {
d = d * d / Math.PI;
}
return d;
}
@Benchmark
public double baseline() {
// simply return the value, this is a baseline
return Math.PI;
}
@Benchmark
public double measureWrong_1() {
// This is wrong: the source is predictable, and computation is foldable.
return compute(Math.PI);
}
@Benchmark
public double measureWrong_2() {
// This is wrong: the source is predictable, and computation is foldable.
return compute(wrongX);
}
@Benchmark
public double measureRight() {
// This is correct: the source is not predictable.
return compute(x);
}
/*
* ============================== HOW TO RUN THIS TEST: ====================================
*
* You can see the unrealistically fast calculation in with measureWrong_*(),
* while realistic measurement with measureRight().
*
* You can run this test:
*
* a) Via the command line:
* $ mvn clean install
* $ java -jar target/benchmarks.jar JMHSample_10 -i 5 -f 1
* (we requested single fork; there are also other options, see -h)
*
* b) Via the Java API:
* (see the JMH homepage for possible caveats when running from IDE:
* http://openjdk.java.net/projects/code-tools/jmh/)
*/
public static void main(String[] args) throws RunnerException {
Options opt = new OptionsBuilder()
.include(JMHSample_10_ConstantFold.class.getSimpleName())
.forks(1)
.build();
new Runner(opt).run();
}
}
| 4,707 | 36.664 | 100 | java |
jmh | jmh-master/jmh-samples/src/main/java/org/openjdk/jmh/samples/JMHSample_11_Loops.java | /*
* Copyright (c) 2014, Oracle America, Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* * Neither the name of Oracle nor the names of its contributors may be used
* to endorse or promote products derived from this software without
* specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
* THE POSSIBILITY OF SUCH DAMAGE.
*/
package org.openjdk.jmh.samples;
import org.openjdk.jmh.annotations.*;
import org.openjdk.jmh.runner.Runner;
import org.openjdk.jmh.runner.RunnerException;
import org.openjdk.jmh.runner.options.Options;
import org.openjdk.jmh.runner.options.OptionsBuilder;
import java.util.concurrent.TimeUnit;
@State(Scope.Thread)
@BenchmarkMode(Mode.AverageTime)
@OutputTimeUnit(TimeUnit.NANOSECONDS)
public class JMHSample_11_Loops {
/*
* It would be tempting for users to do loops within the benchmarked method.
* (This is the bad thing Caliper taught everyone). These tests explain why
* this is a bad idea.
*
* Looping is done in the hope of minimizing the overhead of calling the
* test method, by doing the operations inside the loop instead of inside
* the method call. Don't buy this argument; you will see there is more
* magic happening when we allow optimizers to merge the loop iterations.
*/
/*
* Suppose we want to measure how much it takes to sum two integers:
*/
int x = 1;
int y = 2;
/*
* This is what you do with JMH.
*/
@Benchmark
public int measureRight() {
return (x + y);
}
/*
* The following tests emulate the naive looping.
* This is the Caliper-style benchmark.
*/
private int reps(int reps) {
int s = 0;
for (int i = 0; i < reps; i++) {
s += (x + y);
}
return s;
}
/*
* We would like to measure this with different repetitions count.
* Special annotation is used to get the individual operation cost.
*/
@Benchmark
@OperationsPerInvocation(1)
public int measureWrong_1() {
return reps(1);
}
@Benchmark
@OperationsPerInvocation(10)
public int measureWrong_10() {
return reps(10);
}
@Benchmark
@OperationsPerInvocation(100)
public int measureWrong_100() {
return reps(100);
}
@Benchmark
@OperationsPerInvocation(1_000)
public int measureWrong_1000() {
return reps(1_000);
}
@Benchmark
@OperationsPerInvocation(10_000)
public int measureWrong_10000() {
return reps(10_000);
}
@Benchmark
@OperationsPerInvocation(100_000)
public int measureWrong_100000() {
return reps(100_000);
}
/*
* ============================== HOW TO RUN THIS TEST: ====================================
*
* You might notice the larger the repetitions count, the lower the "perceived"
* cost of the operation being measured. Up to the point we do each addition with 1/20 ns,
* well beyond what hardware can actually do.
*
* This happens because the loop is heavily unrolled/pipelined, and the operation
* to be measured is hoisted from the loop. Moral: don't overuse loops, rely on JMH
* to get the measurement right.
*
* You can run this test:
*
* a) Via the command line:
* $ mvn clean install
* $ java -jar target/benchmarks.jar JMHSample_11 -f 1
* (we requested single fork; there are also other options, see -h)
*
* b) Via the Java API:
* (see the JMH homepage for possible caveats when running from IDE:
* http://openjdk.java.net/projects/code-tools/jmh/)
*/
public static void main(String[] args) throws RunnerException {
Options opt = new OptionsBuilder()
.include(JMHSample_11_Loops.class.getSimpleName())
.forks(1)
.build();
new Runner(opt).run();
}
}
| 5,177 | 31.566038 | 96 | java |
jmh | jmh-master/jmh-samples/src/main/java/org/openjdk/jmh/samples/JMHSample_12_Forking.java | /*
* Copyright (c) 2014, Oracle America, Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* * Neither the name of Oracle nor the names of its contributors may be used
* to endorse or promote products derived from this software without
* specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
* THE POSSIBILITY OF SUCH DAMAGE.
*/
package org.openjdk.jmh.samples;
import org.openjdk.jmh.annotations.*;
import org.openjdk.jmh.runner.Runner;
import org.openjdk.jmh.runner.RunnerException;
import org.openjdk.jmh.runner.options.Options;
import org.openjdk.jmh.runner.options.OptionsBuilder;
import java.util.concurrent.TimeUnit;
@State(Scope.Thread)
@BenchmarkMode(Mode.AverageTime)
@OutputTimeUnit(TimeUnit.NANOSECONDS)
public class JMHSample_12_Forking {
/*
* JVMs are notoriously good at profile-guided optimizations. This is bad
* for benchmarks, because different tests can mix their profiles together,
* and then render the "uniformly bad" code for every test. Forking (running
* in a separate process) each test can help to evade this issue.
*
* JMH will fork the tests by default.
*/
/*
* Suppose we have this simple counter interface, and two implementations.
* Even though those are semantically the same, from the JVM standpoint,
* those are distinct classes.
*/
public interface Counter {
int inc();
}
public static class Counter1 implements Counter {
private int x;
@Override
public int inc() {
return x++;
}
}
public static class Counter2 implements Counter {
private int x;
@Override
public int inc() {
return x++;
}
}
/*
* And this is how we measure it.
* Note this is susceptible for same issue with loops we mention in previous examples.
*/
public int measure(Counter c) {
int s = 0;
for (int i = 0; i < 10; i++) {
s += c.inc();
}
return s;
}
/*
* These are two counters.
*/
Counter c1 = new Counter1();
Counter c2 = new Counter2();
/*
* We first measure the Counter1 alone...
* Fork(0) helps to run in the same JVM.
*/
@Benchmark
@Fork(0)
public int measure_1_c1() {
return measure(c1);
}
/*
* Then Counter2...
*/
@Benchmark
@Fork(0)
public int measure_2_c2() {
return measure(c2);
}
/*
* Then Counter1 again...
*/
@Benchmark
@Fork(0)
public int measure_3_c1_again() {
return measure(c1);
}
/*
* These two tests have explicit @Fork annotation.
* JMH takes this annotation as the request to run the test in the forked JVM.
* It's even simpler to force this behavior for all the tests via the command
* line option "-f". The forking is default, but we still use the annotation
* for the consistency.
*
* This is the test for Counter1.
*/
@Benchmark
@Fork(1)
public int measure_4_forked_c1() {
return measure(c1);
}
/*
* ...and this is the test for Counter2.
*/
@Benchmark
@Fork(1)
public int measure_5_forked_c2() {
return measure(c2);
}
/*
* ============================== HOW TO RUN THIS TEST: ====================================
*
* Note that C1 is faster, C2 is slower, but the C1 is slow again! This is because
* the profiles for C1 and C2 had merged together. Notice how flawless the measurement
* is for forked runs.
*
* You can run this test:
*
* a) Via the command line:
* $ mvn clean install
* $ java -jar target/benchmarks.jar JMHSample_12
*
* b) Via the Java API:
* (see the JMH homepage for possible caveats when running from IDE:
* http://openjdk.java.net/projects/code-tools/jmh/)
*/
public static void main(String[] args) throws RunnerException {
Options opt = new OptionsBuilder()
.include(JMHSample_12_Forking.class.getSimpleName())
.build();
new Runner(opt).run();
}
}
| 5,432 | 28.209677 | 96 | java |
jmh | jmh-master/jmh-samples/src/main/java/org/openjdk/jmh/samples/JMHSample_13_RunToRun.java | /*
* Copyright (c) 2014, Oracle America, Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* * Neither the name of Oracle nor the names of its contributors may be used
* to endorse or promote products derived from this software without
* specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
* THE POSSIBILITY OF SUCH DAMAGE.
*/
package org.openjdk.jmh.samples;
import org.openjdk.jmh.annotations.Benchmark;
import org.openjdk.jmh.annotations.BenchmarkMode;
import org.openjdk.jmh.annotations.Fork;
import org.openjdk.jmh.annotations.Mode;
import org.openjdk.jmh.annotations.OutputTimeUnit;
import org.openjdk.jmh.annotations.Scope;
import org.openjdk.jmh.annotations.Setup;
import org.openjdk.jmh.annotations.State;
import org.openjdk.jmh.runner.Runner;
import org.openjdk.jmh.runner.RunnerException;
import org.openjdk.jmh.runner.options.Options;
import org.openjdk.jmh.runner.options.OptionsBuilder;
import java.util.concurrent.TimeUnit;
@State(Scope.Thread)
@BenchmarkMode(Mode.AverageTime)
@OutputTimeUnit(TimeUnit.MILLISECONDS)
public class JMHSample_13_RunToRun {
/*
* Forking also allows to estimate run-to-run variance.
*
* JVMs are complex systems, and the non-determinism is inherent for them.
* This requires us to always account the run-to-run variance as the one
* of the effects in our experiments.
*
* Luckily, forking aggregates the results across several JVM launches.
*/
/*
* In order to introduce readily measurable run-to-run variance, we build
* the workload which performance differs from run to run. Note that many workloads
* will have the similar behavior, but we do that artificially to make a point.
*/
@State(Scope.Thread)
public static class SleepyState {
public long sleepTime;
@Setup
public void setup() {
sleepTime = (long) (Math.random() * 1000);
}
}
/*
* Now, we will run this different number of times.
*/
@Benchmark
@Fork(1)
public void baseline(SleepyState s) throws InterruptedException {
TimeUnit.MILLISECONDS.sleep(s.sleepTime);
}
@Benchmark
@Fork(5)
public void fork_1(SleepyState s) throws InterruptedException {
TimeUnit.MILLISECONDS.sleep(s.sleepTime);
}
@Benchmark
@Fork(20)
public void fork_2(SleepyState s) throws InterruptedException {
TimeUnit.MILLISECONDS.sleep(s.sleepTime);
}
/*
* ============================== HOW TO RUN THIS TEST: ====================================
*
* Note the baseline is random within [0..1000] msec; and both forked runs
* are estimating the average 500 msec with some confidence.
*
* You can run this test:
*
* a) Via the command line:
* $ mvn clean install
* $ java -jar target/benchmarks.jar JMHSample_13 -wi 0 -i 3
* (we requested no warmup, 3 measurement iterations; there are also other options, see -h)
*
* b) Via the Java API:
* (see the JMH homepage for possible caveats when running from IDE:
* http://openjdk.java.net/projects/code-tools/jmh/)
*/
public static void main(String[] args) throws RunnerException {
Options opt = new OptionsBuilder()
.include(JMHSample_13_RunToRun.class.getSimpleName())
.warmupIterations(0)
.measurementIterations(3)
.build();
new Runner(opt).run();
}
}
| 4,737 | 35.446154 | 98 | java |
jmh | jmh-master/jmh-samples/src/main/java/org/openjdk/jmh/samples/JMHSample_15_Asymmetric.java | /*
* Copyright (c) 2014, Oracle America, Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* * Neither the name of Oracle nor the names of its contributors may be used
* to endorse or promote products derived from this software without
* specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
* THE POSSIBILITY OF SUCH DAMAGE.
*/
package org.openjdk.jmh.samples;
import org.openjdk.jmh.annotations.Benchmark;
import org.openjdk.jmh.annotations.BenchmarkMode;
import org.openjdk.jmh.annotations.Group;
import org.openjdk.jmh.annotations.GroupThreads;
import org.openjdk.jmh.annotations.Mode;
import org.openjdk.jmh.annotations.OutputTimeUnit;
import org.openjdk.jmh.annotations.Scope;
import org.openjdk.jmh.annotations.Setup;
import org.openjdk.jmh.annotations.State;
import org.openjdk.jmh.runner.Runner;
import org.openjdk.jmh.runner.RunnerException;
import org.openjdk.jmh.runner.options.Options;
import org.openjdk.jmh.runner.options.OptionsBuilder;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
@State(Scope.Group)
@BenchmarkMode(Mode.AverageTime)
@OutputTimeUnit(TimeUnit.NANOSECONDS)
public class JMHSample_15_Asymmetric {
/*
* So far all the tests were symmetric: the same code was executed in all the threads.
* At times, you need the asymmetric test. JMH provides this with the notion of @Group,
* which can bind several methods together, and all the threads are distributed among
* the test methods.
*
* Each execution group contains of one or more threads. Each thread within a particular
* execution group executes one of @Group-annotated @Benchmark methods. Multiple execution
* groups may participate in the run. The total thread count in the run is rounded to the
* execution group size, which will only allow the full execution groups.
*
* Note that two state scopes: Scope.Benchmark and Scope.Thread are not covering all
* the use cases here -- you either share everything in the state, or share nothing.
* To break this, we have the middle ground Scope.Group, which marks the state to be
* shared within the execution group, but not among the execution groups.
*
* Putting this all together, the example below means:
* a) define the execution group "g", with 3 threads executing inc(), and 1 thread
* executing get(), 4 threads per group in total;
* b) if we run this test case with 4 threads, then we will have a single execution
* group. Generally, running with 4*N threads will create N execution groups, etc.;
* c) each execution group has one @State instance to share: that is, execution groups
* share the counter within the group, but not across the groups.
*/
private AtomicInteger counter;
@Setup
public void up() {
counter = new AtomicInteger();
}
@Benchmark
@Group("g")
@GroupThreads(3)
public int inc() {
return counter.incrementAndGet();
}
@Benchmark
@Group("g")
@GroupThreads(1)
public int get() {
return counter.get();
}
/*
* ============================== HOW TO RUN THIS TEST: ====================================
*
* You will have the distinct metrics for inc() and get() from this run.
*
* You can run this test:
*
* a) Via the command line:
* $ mvn clean install
* $ java -jar target/benchmarks.jar JMHSample_15 -f 1
* (we requested single fork; there are also other options, see -h)
*
* b) Via the Java API:
* (see the JMH homepage for possible caveats when running from IDE:
* http://openjdk.java.net/projects/code-tools/jmh/)
*/
public static void main(String[] args) throws RunnerException {
Options opt = new OptionsBuilder()
.include(JMHSample_15_Asymmetric.class.getSimpleName())
.forks(1)
.build();
new Runner(opt).run();
}
}
| 5,257 | 40.078125 | 96 | java |
jmh | jmh-master/jmh-samples/src/main/java/org/openjdk/jmh/samples/JMHSample_16_CompilerControl.java | /*
* Copyright (c) 2014, Oracle America, Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* * Neither the name of Oracle nor the names of its contributors may be used
* to endorse or promote products derived from this software without
* specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
* THE POSSIBILITY OF SUCH DAMAGE.
*/
package org.openjdk.jmh.samples;
import org.openjdk.jmh.annotations.Benchmark;
import org.openjdk.jmh.annotations.BenchmarkMode;
import org.openjdk.jmh.annotations.CompilerControl;
import org.openjdk.jmh.annotations.Mode;
import org.openjdk.jmh.annotations.OutputTimeUnit;
import org.openjdk.jmh.annotations.Scope;
import org.openjdk.jmh.annotations.State;
import org.openjdk.jmh.runner.Runner;
import org.openjdk.jmh.runner.RunnerException;
import org.openjdk.jmh.runner.options.Options;
import org.openjdk.jmh.runner.options.OptionsBuilder;
import java.util.concurrent.TimeUnit;
@State(Scope.Thread)
@BenchmarkMode(Mode.AverageTime)
@OutputTimeUnit(TimeUnit.NANOSECONDS)
public class JMHSample_16_CompilerControl {
/*
* We can use HotSpot-specific functionality to tell the compiler what
* do we want to do with particular methods. To demonstrate the effects,
* we end up with 3 methods in this sample.
*/
/**
* These are our targets:
* - first method is prohibited from inlining
* - second method is forced to inline
* - third method is prohibited from compiling
*
* We might even place the annotations directly to the benchmarked
* methods, but this expresses the intent more clearly.
*/
public void target_blank() {
// this method was intentionally left blank
}
@CompilerControl(CompilerControl.Mode.DONT_INLINE)
public void target_dontInline() {
// this method was intentionally left blank
}
@CompilerControl(CompilerControl.Mode.INLINE)
public void target_inline() {
// this method was intentionally left blank
}
@CompilerControl(CompilerControl.Mode.EXCLUDE)
public void target_exclude() {
// this method was intentionally left blank
}
/*
* These method measures the calls performance.
*/
@Benchmark
public void baseline() {
// this method was intentionally left blank
}
@Benchmark
public void blank() {
target_blank();
}
@Benchmark
public void dontinline() {
target_dontInline();
}
@Benchmark
public void inline() {
target_inline();
}
@Benchmark
public void exclude() {
target_exclude();
}
/*
* ============================== HOW TO RUN THIS TEST: ====================================
*
* Note the performance of the baseline, blank, and inline methods are the same.
* dontinline differs a bit, because we are making the proper call.
* exclude is severely slower, becase we are not compiling it at all.
*
* You can run this test:
*
* a) Via the command line:
* $ mvn clean install
* $ java -jar target/benchmarks.jar JMHSample_16 -wi 0 -i 3 -f 1
* (we requested no warmup iterations, 3 iterations, single fork; there are also other options, see -h)
*
* b) Via the Java API:
* (see the JMH homepage for possible caveats when running from IDE:
* http://openjdk.java.net/projects/code-tools/jmh/)
*/
public static void main(String[] args) throws RunnerException {
Options opt = new OptionsBuilder()
.include(JMHSample_16_CompilerControl.class.getSimpleName())
.warmupIterations(0)
.measurementIterations(3)
.forks(1)
.build();
new Runner(opt).run();
}
}
| 5,031 | 33.231293 | 110 | java |
jmh | jmh-master/jmh-samples/src/main/java/org/openjdk/jmh/samples/JMHSample_17_SyncIterations.java | /*
* Copyright (c) 2014, Oracle America, Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* * Neither the name of Oracle nor the names of its contributors may be used
* to endorse or promote products derived from this software without
* specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
* THE POSSIBILITY OF SUCH DAMAGE.
*/
package org.openjdk.jmh.samples;
import org.openjdk.jmh.annotations.Benchmark;
import org.openjdk.jmh.annotations.OutputTimeUnit;
import org.openjdk.jmh.annotations.Scope;
import org.openjdk.jmh.annotations.State;
import org.openjdk.jmh.runner.Runner;
import org.openjdk.jmh.runner.RunnerException;
import org.openjdk.jmh.runner.options.Options;
import org.openjdk.jmh.runner.options.OptionsBuilder;
import org.openjdk.jmh.runner.options.TimeValue;
import java.util.concurrent.TimeUnit;
@State(Scope.Thread)
@OutputTimeUnit(TimeUnit.MILLISECONDS)
public class JMHSample_17_SyncIterations {
/*
* This is the another thing that is enabled in JMH by default.
*
* Suppose we have this simple benchmark.
*/
private double src;
@Benchmark
public double test() {
double s = src;
for (int i = 0; i < 1000; i++) {
s = Math.sin(s);
}
return s;
}
/*
* It turns out if you run the benchmark with multiple threads,
* the way you start and stop the worker threads seriously affects
* performance.
*
* The natural way would be to park all the threads on some sort
* of barrier, and the let them go "at once". However, that does
* not work: there are no guarantees the worker threads will start
* at the same time, meaning other worker threads are working
* in better conditions, skewing the result.
*
* The better solution would be to introduce bogus iterations,
* ramp up the threads executing the iterations, and then atomically
* shift the system to measuring stuff. The same thing can be done
* during the rampdown. This sounds complicated, but JMH already
* handles that for you.
*
*/
/*
* ============================== HOW TO RUN THIS TEST: ====================================
*
* You will need to oversubscribe the system to make this effect
* clearly visible; however, this effect can also be shown on the
* unsaturated systems.*
*
* Note the performance of -si false version is more flaky, even
* though it is "better". This is the false improvement, granted by
* some of the threads executing in solo. The -si true version more stable
* and coherent.
*
* -si true is enabled by default.
*
* Say, $CPU is the number of CPUs on your machine.
*
* You can run this test with:
*
* a) Via the command line:
* $ mvn clean install
* $ java -jar target/benchmarks.jar JMHSample_17 \
* -w 1s -r 1s -f 1 -t ${CPU*16} -si {true|false}
* (we requested shorter warmup/measurement iterations, single fork,
* lots of threads, and changeable "synchronize iterations" option)
*
* b) Via the Java API:
* (see the JMH homepage for possible caveats when running from IDE:
* http://openjdk.java.net/projects/code-tools/jmh/)
*/
public static void main(String[] args) throws RunnerException {
Options opt = new OptionsBuilder()
.include(JMHSample_17_SyncIterations.class.getSimpleName())
.warmupTime(TimeValue.seconds(1))
.measurementTime(TimeValue.seconds(1))
.threads(Runtime.getRuntime().availableProcessors()*16)
.forks(1)
.syncIterations(true) // try to switch to "false"
.build();
new Runner(opt).run();
}
}
| 5,059 | 37.923077 | 96 | java |
jmh | jmh-master/jmh-samples/src/main/java/org/openjdk/jmh/samples/JMHSample_18_Control.java | /*
* Copyright (c) 2014, Oracle America, Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* * Neither the name of Oracle nor the names of its contributors may be used
* to endorse or promote products derived from this software without
* specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
* THE POSSIBILITY OF SUCH DAMAGE.
*/
package org.openjdk.jmh.samples;
import org.openjdk.jmh.annotations.Benchmark;
import org.openjdk.jmh.annotations.Group;
import org.openjdk.jmh.annotations.Scope;
import org.openjdk.jmh.annotations.State;
import org.openjdk.jmh.infra.Control;
import org.openjdk.jmh.runner.Runner;
import org.openjdk.jmh.runner.RunnerException;
import org.openjdk.jmh.runner.options.Options;
import org.openjdk.jmh.runner.options.OptionsBuilder;
import java.util.concurrent.atomic.AtomicBoolean;
@State(Scope.Group)
public class JMHSample_18_Control {
/*
* Sometimes you need the tap into the harness mind to get the info
* on the transition change. For this, we have the experimental state object,
* Control, which is updated by JMH as we go.
*/
/*
* In this example, we want to estimate the ping-pong speed for the simple
* AtomicBoolean. Unfortunately, doing that in naive manner will livelock
* one of the threads, because the executions of ping/pong are not paired
* perfectly. We need the escape hatch to terminate the loop if threads
* are about to leave the measurement.
*/
public final AtomicBoolean flag = new AtomicBoolean();
@Benchmark
@Group("pingpong")
public void ping(Control cnt) {
while (!cnt.stopMeasurement && !flag.compareAndSet(false, true)) {
// this body is intentionally left blank
}
}
@Benchmark
@Group("pingpong")
public void pong(Control cnt) {
while (!cnt.stopMeasurement && !flag.compareAndSet(true, false)) {
// this body is intentionally left blank
}
}
/*
* ============================== HOW TO RUN THIS TEST: ====================================
*
* You can run this test:
*
* a) Via the command line:
* $ mvn clean install
* $ java -jar target/benchmarks.jar JMHSample_18 -t 2 -f 1
* (we requested 2 threads and single fork; there are also other options, see -h)
*
* b) Via the Java API:
* (see the JMH homepage for possible caveats when running from IDE:
* http://openjdk.java.net/projects/code-tools/jmh/)
*/
public static void main(String[] args) throws RunnerException {
Options opt = new OptionsBuilder()
.include(JMHSample_18_Control.class.getSimpleName())
.threads(2)
.forks(1)
.build();
new Runner(opt).run();
}
}
| 4,054 | 37.254717 | 96 | java |
jmh | jmh-master/jmh-samples/src/main/java/org/openjdk/jmh/samples/JMHSample_20_Annotations.java | /*
* Copyright (c) 2014, Oracle America, Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* * Neither the name of Oracle nor the names of its contributors may be used
* to endorse or promote products derived from this software without
* specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
* THE POSSIBILITY OF SUCH DAMAGE.
*/
package org.openjdk.jmh.samples;
import org.openjdk.jmh.annotations.Benchmark;
import org.openjdk.jmh.annotations.Fork;
import org.openjdk.jmh.annotations.Measurement;
import org.openjdk.jmh.annotations.OutputTimeUnit;
import org.openjdk.jmh.annotations.Scope;
import org.openjdk.jmh.annotations.State;
import org.openjdk.jmh.annotations.Warmup;
import org.openjdk.jmh.runner.Runner;
import org.openjdk.jmh.runner.RunnerException;
import org.openjdk.jmh.runner.options.Options;
import org.openjdk.jmh.runner.options.OptionsBuilder;
import java.util.concurrent.TimeUnit;
@State(Scope.Thread)
@OutputTimeUnit(TimeUnit.MICROSECONDS)
@Fork(1)
public class JMHSample_20_Annotations {
double x1 = Math.PI;
/*
* In addition to all the command line options usable at run time,
* we have the annotations which can provide the reasonable defaults
* for the some of the benchmarks. This is very useful when you are
* dealing with lots of benchmarks, and some of them require
* special treatment.
*
* Annotation can also be placed on class, to have the effect over
* all the benchmark methods in the same class. The rule is, the
* annotation in the closest scope takes the precedence: i.e.
* the method-based annotation overrides class-based annotation,
* etc.
*/
@Benchmark
@Warmup(iterations = 5, time = 100, timeUnit = TimeUnit.MILLISECONDS)
@Measurement(iterations = 5, time = 100, timeUnit = TimeUnit.MILLISECONDS)
public double measure() {
return Math.log(x1);
}
/*
* ============================== HOW TO RUN THIS TEST: ====================================
*
* Note JMH honors the default annotation settings. You can always override
* the defaults via the command line or API.
*
* You can run this test:
*
* a) Via the command line:
* $ mvn clean install
* $ java -jar target/benchmarks.jar JMHSample_20
*
* b) Via the Java API:
* (see the JMH homepage for possible caveats when running from IDE:
* http://openjdk.java.net/projects/code-tools/jmh/)
*/
public static void main(String[] args) throws RunnerException {
Options opt = new OptionsBuilder()
.include(JMHSample_20_Annotations.class.getSimpleName())
.build();
new Runner(opt).run();
}
}
| 3,974 | 38.356436 | 96 | java |
jmh | jmh-master/jmh-samples/src/main/java/org/openjdk/jmh/samples/JMHSample_21_ConsumeCPU.java | /*
* Copyright (c) 2014, Oracle America, Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* * Neither the name of Oracle nor the names of its contributors may be used
* to endorse or promote products derived from this software without
* specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
* THE POSSIBILITY OF SUCH DAMAGE.
*/
package org.openjdk.jmh.samples;
import org.openjdk.jmh.annotations.Benchmark;
import org.openjdk.jmh.annotations.BenchmarkMode;
import org.openjdk.jmh.annotations.Mode;
import org.openjdk.jmh.annotations.OutputTimeUnit;
import org.openjdk.jmh.infra.Blackhole;
import org.openjdk.jmh.runner.Runner;
import org.openjdk.jmh.runner.RunnerException;
import org.openjdk.jmh.runner.options.Options;
import org.openjdk.jmh.runner.options.OptionsBuilder;
import java.util.concurrent.TimeUnit;
@BenchmarkMode(Mode.AverageTime)
@OutputTimeUnit(TimeUnit.NANOSECONDS)
public class JMHSample_21_ConsumeCPU {
/*
* At times you require the test to burn some of the cycles doing nothing.
* In many cases, you *do* want to burn the cycles instead of waiting.
*
* For these occasions, we have the infrastructure support. Blackholes
* can not only consume the values, but also the time! Run this test
* to get familiar with this part of JMH.
*
* (Note we use static method because most of the use cases are deep
* within the testing code, and propagating blackholes is tedious).
*/
@Benchmark
public void consume_0000() {
Blackhole.consumeCPU(0);
}
@Benchmark
public void consume_0001() {
Blackhole.consumeCPU(1);
}
@Benchmark
public void consume_0002() {
Blackhole.consumeCPU(2);
}
@Benchmark
public void consume_0004() {
Blackhole.consumeCPU(4);
}
@Benchmark
public void consume_0008() {
Blackhole.consumeCPU(8);
}
@Benchmark
public void consume_0016() {
Blackhole.consumeCPU(16);
}
@Benchmark
public void consume_0032() {
Blackhole.consumeCPU(32);
}
@Benchmark
public void consume_0064() {
Blackhole.consumeCPU(64);
}
@Benchmark
public void consume_0128() {
Blackhole.consumeCPU(128);
}
@Benchmark
public void consume_0256() {
Blackhole.consumeCPU(256);
}
@Benchmark
public void consume_0512() {
Blackhole.consumeCPU(512);
}
@Benchmark
public void consume_1024() {
Blackhole.consumeCPU(1024);
}
/*
* ============================== HOW TO RUN THIS TEST: ====================================
*
* Note the single token is just a few cycles, and the more tokens
* you request, then more work is spent (almost linearly)
*
* You can run this test:
*
* a) Via the command line:
* $ mvn clean install
* $ java -jar target/benchmarks.jar JMHSample_21 -f 1
* (we requested single fork; there are also other options, see -h)
*
* b) Via the Java API:
* (see the JMH homepage for possible caveats when running from IDE:
* http://openjdk.java.net/projects/code-tools/jmh/)
*/
public static void main(String[] args) throws RunnerException {
Options opt = new OptionsBuilder()
.include(JMHSample_21_ConsumeCPU.class.getSimpleName())
.forks(1)
.build();
new Runner(opt).run();
}
}
| 4,713 | 30.637584 | 96 | java |
jmh | jmh-master/jmh-samples/src/main/java/org/openjdk/jmh/samples/JMHSample_22_FalseSharing.java | /*
* Copyright (c) 2014, Oracle America, Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* * Neither the name of Oracle nor the names of its contributors may be used
* to endorse or promote products derived from this software without
* specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
* THE POSSIBILITY OF SUCH DAMAGE.
*/
package org.openjdk.jmh.samples;
import org.openjdk.jmh.annotations.Benchmark;
import org.openjdk.jmh.annotations.BenchmarkMode;
import org.openjdk.jmh.annotations.Fork;
import org.openjdk.jmh.annotations.Group;
import org.openjdk.jmh.annotations.Measurement;
import org.openjdk.jmh.annotations.Mode;
import org.openjdk.jmh.annotations.OutputTimeUnit;
import org.openjdk.jmh.annotations.Scope;
import org.openjdk.jmh.annotations.State;
import org.openjdk.jmh.annotations.Warmup;
import org.openjdk.jmh.runner.Runner;
import org.openjdk.jmh.runner.RunnerException;
import org.openjdk.jmh.runner.options.Options;
import org.openjdk.jmh.runner.options.OptionsBuilder;
import java.util.concurrent.TimeUnit;
@BenchmarkMode(Mode.Throughput)
@OutputTimeUnit(TimeUnit.MICROSECONDS)
@Warmup(iterations = 5, time = 1, timeUnit = TimeUnit.SECONDS)
@Measurement(iterations = 5, time = 1, timeUnit = TimeUnit.SECONDS)
@Fork(5)
public class JMHSample_22_FalseSharing {
/*
* One of the unusual thing that can bite you back is false sharing.
* If two threads access (and possibly modify) the adjacent values
* in memory, chances are, they are modifying the values on the same
* cache line. This can yield significant (artificial) slowdowns.
*
* JMH helps you to alleviate this: @States are automatically padded.
* This padding does not extend to the State internals though,
* as we will see in this example. You have to take care of this on
* your own.
*/
/*
* Suppose we have two threads:
* a) innocuous reader which blindly reads its own field
* b) furious writer which updates its own field
*/
/*
* BASELINE EXPERIMENT:
* Because of the false sharing, both reader and writer will experience
* penalties.
*/
@State(Scope.Group)
public static class StateBaseline {
int readOnly;
int writeOnly;
}
@Benchmark
@Group("baseline")
public int reader(StateBaseline s) {
return s.readOnly;
}
@Benchmark
@Group("baseline")
public void writer(StateBaseline s) {
s.writeOnly++;
}
/*
* APPROACH 1: PADDING
*
* We can try to alleviate some of the effects with padding.
* This is not versatile because JVMs can freely rearrange the
* field order, even of the same type.
*/
@State(Scope.Group)
public static class StatePadded {
int readOnly;
int p01, p02, p03, p04, p05, p06, p07, p08;
int p11, p12, p13, p14, p15, p16, p17, p18;
int writeOnly;
int q01, q02, q03, q04, q05, q06, q07, q08;
int q11, q12, q13, q14, q15, q16, q17, q18;
}
@Benchmark
@Group("padded")
public int reader(StatePadded s) {
return s.readOnly;
}
@Benchmark
@Group("padded")
public void writer(StatePadded s) {
s.writeOnly++;
}
/*
* APPROACH 2: CLASS HIERARCHY TRICK
*
* We can alleviate false sharing with this convoluted hierarchy trick,
* using the fact that superclass fields are usually laid out first.
* In this construction, the protected field will be squashed between
* paddings.
* It is important to use the smallest data type, so that layouter would
* not generate any gaps that can be taken by later protected subclasses
* fields. Depending on the actual field layout of classes that bear the
* protected fields, we might need more padding to account for "lost"
* padding fields pulled into in their superclass gaps.
*/
public static class StateHierarchy_1 {
int readOnly;
}
public static class StateHierarchy_2 extends StateHierarchy_1 {
byte p01, p02, p03, p04, p05, p06, p07, p08;
byte p11, p12, p13, p14, p15, p16, p17, p18;
byte p21, p22, p23, p24, p25, p26, p27, p28;
byte p31, p32, p33, p34, p35, p36, p37, p38;
byte p41, p42, p43, p44, p45, p46, p47, p48;
byte p51, p52, p53, p54, p55, p56, p57, p58;
byte p61, p62, p63, p64, p65, p66, p67, p68;
byte p71, p72, p73, p74, p75, p76, p77, p78;
}
public static class StateHierarchy_3 extends StateHierarchy_2 {
int writeOnly;
}
public static class StateHierarchy_4 extends StateHierarchy_3 {
byte q01, q02, q03, q04, q05, q06, q07, q08;
byte q11, q12, q13, q14, q15, q16, q17, q18;
byte q21, q22, q23, q24, q25, q26, q27, q28;
byte q31, q32, q33, q34, q35, q36, q37, q38;
byte q41, q42, q43, q44, q45, q46, q47, q48;
byte q51, q52, q53, q54, q55, q56, q57, q58;
byte q61, q62, q63, q64, q65, q66, q67, q68;
byte q71, q72, q73, q74, q75, q76, q77, q78;
}
@State(Scope.Group)
public static class StateHierarchy extends StateHierarchy_4 {
}
@Benchmark
@Group("hierarchy")
public int reader(StateHierarchy s) {
return s.readOnly;
}
@Benchmark
@Group("hierarchy")
public void writer(StateHierarchy s) {
s.writeOnly++;
}
/*
* APPROACH 3: ARRAY TRICK
*
* This trick relies on the contiguous allocation of an array.
* Instead of placing the fields in the class, we mangle them
* into the array at very sparse offsets.
*/
@State(Scope.Group)
public static class StateArray {
int[] arr = new int[128];
}
@Benchmark
@Group("sparse")
public int reader(StateArray s) {
return s.arr[0];
}
@Benchmark
@Group("sparse")
public void writer(StateArray s) {
s.arr[64]++;
}
/*
* APPROACH 4:
*
* @Contended (since JDK 8):
* Uncomment the annotation if building with JDK 8.
* Remember to flip -XX:-RestrictContended to enable.
*/
@State(Scope.Group)
public static class StateContended {
int readOnly;
// @sun.misc.Contended
int writeOnly;
}
@Benchmark
@Group("contended")
public int reader(StateContended s) {
return s.readOnly;
}
@Benchmark
@Group("contended")
public void writer(StateContended s) {
s.writeOnly++;
}
/*
* ============================== HOW TO RUN THIS TEST: ====================================
*
* Note the slowdowns.
*
* You can run this test:
*
* a) Via the command line:
* $ mvn clean install
* $ java -jar target/benchmarks.jar JMHSample_22 -t $CPU
*
* b) Via the Java API:
* (see the JMH homepage for possible caveats when running from IDE:
* http://openjdk.java.net/projects/code-tools/jmh/)
*/
public static void main(String[] args) throws RunnerException {
Options opt = new OptionsBuilder()
.include(JMHSample_22_FalseSharing.class.getSimpleName())
.threads(Runtime.getRuntime().availableProcessors())
.build();
new Runner(opt).run();
}
}
| 8,570 | 30.862454 | 96 | java |
jmh | jmh-master/jmh-samples/src/main/java/org/openjdk/jmh/samples/JMHSample_23_AuxCounters.java | /*
* Copyright (c) 2014, Oracle America, Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* * Neither the name of Oracle nor the names of its contributors may be used
* to endorse or promote products derived from this software without
* specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
* THE POSSIBILITY OF SUCH DAMAGE.
*/
package org.openjdk.jmh.samples;
import org.openjdk.jmh.annotations.AuxCounters;
import org.openjdk.jmh.annotations.Benchmark;
import org.openjdk.jmh.annotations.Fork;
import org.openjdk.jmh.annotations.Measurement;
import org.openjdk.jmh.annotations.OutputTimeUnit;
import org.openjdk.jmh.annotations.Scope;
import org.openjdk.jmh.annotations.State;
import org.openjdk.jmh.annotations.Warmup;
import org.openjdk.jmh.runner.Runner;
import org.openjdk.jmh.runner.RunnerException;
import org.openjdk.jmh.runner.options.Options;
import org.openjdk.jmh.runner.options.OptionsBuilder;
import java.util.concurrent.TimeUnit;
@OutputTimeUnit(TimeUnit.SECONDS)
@Warmup(iterations = 5, time = 1, timeUnit = TimeUnit.SECONDS)
@Measurement(iterations = 5, time = 1, timeUnit = TimeUnit.SECONDS)
@Fork(1)
public class JMHSample_23_AuxCounters {
/*
* In some weird cases you need to get the separate throughput/time
* metrics for the benchmarked code depending on the outcome of the
* current code. Trying to accommodate the cases like this, JMH optionally
* provides the special annotation which treats @State objects
* as the object bearing user counters. See @AuxCounters javadoc for
* the limitations.
*/
@State(Scope.Thread)
@AuxCounters(AuxCounters.Type.OPERATIONS)
public static class OpCounters {
// These fields would be counted as metrics
public int case1;
public int case2;
// This accessor will also produce a metric
public int total() {
return case1 + case2;
}
}
@State(Scope.Thread)
@AuxCounters(AuxCounters.Type.EVENTS)
public static class EventCounters {
// This field would be counted as metric
public int wows;
}
/*
* This code measures the "throughput" in two parts of the branch.
* The @AuxCounters state above holds the counters which we increment
* ourselves, and then let JMH to use their values in the performance
* calculations.
*/
@Benchmark
public void splitBranch(OpCounters counters) {
if (Math.random() < 0.1) {
counters.case1++;
} else {
counters.case2++;
}
}
@Benchmark
public void runSETI(EventCounters counters) {
float random = (float) Math.random();
float wowSignal = (float) Math.PI / 4;
if (random == wowSignal) {
// WOW, that's unusual.
counters.wows++;
}
}
/*
* ============================== HOW TO RUN THIS TEST: ====================================
*
* You can run this test:
*
* a) Via the command line:
* $ mvn clean install
* $ java -jar target/benchmarks.jar JMHSample_23
*
* b) Via the Java API:
* (see the JMH homepage for possible caveats when running from IDE:
* http://openjdk.java.net/projects/code-tools/jmh/)
*/
public static void main(String[] args) throws RunnerException {
Options opt = new OptionsBuilder()
.include(JMHSample_23_AuxCounters.class.getSimpleName())
.build();
new Runner(opt).run();
}
}
| 4,776 | 35.189394 | 96 | java |
jmh | jmh-master/jmh-samples/src/main/java/org/openjdk/jmh/samples/JMHSample_24_Inheritance.java | /*
* Copyright (c) 2014, Oracle America, Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* * Neither the name of Oracle nor the names of its contributors may be used
* to endorse or promote products derived from this software without
* specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
* THE POSSIBILITY OF SUCH DAMAGE.
*/
package org.openjdk.jmh.samples;
import org.openjdk.jmh.annotations.Benchmark;
import org.openjdk.jmh.annotations.BenchmarkMode;
import org.openjdk.jmh.annotations.Fork;
import org.openjdk.jmh.annotations.Measurement;
import org.openjdk.jmh.annotations.Mode;
import org.openjdk.jmh.annotations.OutputTimeUnit;
import org.openjdk.jmh.annotations.Scope;
import org.openjdk.jmh.annotations.Setup;
import org.openjdk.jmh.annotations.State;
import org.openjdk.jmh.annotations.Warmup;
import org.openjdk.jmh.runner.Runner;
import org.openjdk.jmh.runner.RunnerException;
import org.openjdk.jmh.runner.options.Options;
import org.openjdk.jmh.runner.options.OptionsBuilder;
import java.util.concurrent.TimeUnit;
public class JMHSample_24_Inheritance {
/*
* In very special circumstances, you might want to provide the benchmark
* body in the (abstract) superclass, and specialize it with the concrete
* pieces in the subclasses.
*
* The rule of thumb is: if some class has @Benchmark method, then all the subclasses
* are also having the "synthetic" @Benchmark method. The caveat is, because we only
* know the type hierarchy during the compilation, it is only possible during
* the same compilation session. That is, mixing in the subclass extending your
* benchmark class *after* the JMH compilation would have no effect.
*
* Note how annotations now have two possible places. The closest annotation
* in the hierarchy wins.
*/
@BenchmarkMode(Mode.AverageTime)
@Fork(1)
@State(Scope.Thread)
@OutputTimeUnit(TimeUnit.NANOSECONDS)
public static abstract class AbstractBenchmark {
int x;
@Setup
public void setup() {
x = 42;
}
@Benchmark
@Warmup(iterations = 5, time = 100, timeUnit = TimeUnit.MILLISECONDS)
@Measurement(iterations = 5, time = 100, timeUnit = TimeUnit.MILLISECONDS)
public double bench() {
return doWork() * doWork();
}
protected abstract double doWork();
}
public static class BenchmarkLog extends AbstractBenchmark {
@Override
protected double doWork() {
return Math.log(x);
}
}
public static class BenchmarkSin extends AbstractBenchmark {
@Override
protected double doWork() {
return Math.sin(x);
}
}
public static class BenchmarkCos extends AbstractBenchmark {
@Override
protected double doWork() {
return Math.cos(x);
}
}
/*
* ============================== HOW TO RUN THIS TEST: ====================================
*
* You can run this test, and observe the three distinct benchmarks running the squares
* of Math.log, Math.sin, and Math.cos, accordingly.
*
* a) Via the command line:
* $ mvn clean install
* $ java -jar target/benchmarks.jar JMHSample_24
*
* b) Via the Java API:
* (see the JMH homepage for possible caveats when running from IDE:
* http://openjdk.java.net/projects/code-tools/jmh/)
*/
public static void main(String[] args) throws RunnerException {
Options opt = new OptionsBuilder()
.include(JMHSample_24_Inheritance.class.getSimpleName())
.build();
new Runner(opt).run();
}
}
| 4,972 | 36.11194 | 96 | java |
jmh | jmh-master/jmh-samples/src/main/java/org/openjdk/jmh/samples/JMHSample_25_API_GA.java | /*
* Copyright (c) 2014, Oracle America, Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* * Neither the name of Oracle nor the names of its contributors may be used
* to endorse or promote products derived from this software without
* specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
* THE POSSIBILITY OF SUCH DAMAGE.
*/
package org.openjdk.jmh.samples;
import org.openjdk.jmh.annotations.Benchmark;
import org.openjdk.jmh.annotations.Scope;
import org.openjdk.jmh.annotations.State;
import org.openjdk.jmh.results.Result;
import org.openjdk.jmh.results.RunResult;
import org.openjdk.jmh.runner.Runner;
import org.openjdk.jmh.runner.RunnerException;
import org.openjdk.jmh.runner.options.Options;
import org.openjdk.jmh.runner.options.OptionsBuilder;
import org.openjdk.jmh.runner.options.TimeValue;
import org.openjdk.jmh.runner.options.VerboseMode;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
@State(Scope.Thread)
public class JMHSample_25_API_GA {
/**
* This example shows the rather convoluted, but fun way to exploit
* JMH API in complex scenarios. Up to this point, we haven't consumed
* the results programmatically, and hence we are missing all the fun.
*
* Let's consider this naive code, which obviously suffers from the
* performance anomalies, since current HotSpot is resistant to make
* the tail-call optimizations.
*/
private int v;
@Benchmark
public int test() {
return veryImportantCode(1000, v);
}
public int veryImportantCode(int d, int v) {
if (d == 0) {
return v;
} else {
return veryImportantCode(d - 1, v);
}
}
/*
* We could probably make up for the absence of TCO with better inlining
* policy. But hand-tuning the policy requires knowing a lot about VM
* internals. Let's instead construct the layman's genetic algorithm
* which sifts through inlining settings trying to find the better policy.
*
* If you are not familiar with the concept of Genetic Algorithms,
* read the Wikipedia article first:
* http://en.wikipedia.org/wiki/Genetic_algorithm
*
* VM experts can guess which option should be tuned to get the max
* performance. Try to run the sample and see if it improves performance.
*/
public static void main(String[] args) throws RunnerException {
// These are our base options. We will mix these options into the
// measurement runs. That is, all measurement runs will inherit these,
// see how it's done below.
Options baseOpts = new OptionsBuilder()
.include(JMHSample_25_API_GA.class.getName())
.warmupTime(TimeValue.milliseconds(200))
.measurementTime(TimeValue.milliseconds(200))
.warmupIterations(5)
.measurementIterations(5)
.forks(1)
.verbosity(VerboseMode.SILENT)
.build();
// Initial population
Population pop = new Population();
final int POPULATION = 10;
for (int c = 0; c < POPULATION; c++) {
pop.addChromosome(new Chromosome(baseOpts));
}
// Make a few rounds of optimization:
final int GENERATIONS = 100;
for (int g = 0; g < GENERATIONS; g++) {
System.out.println("Entering generation " + g);
// Get the baseline score.
// We opt to remeasure it in order to get reliable current estimate.
RunResult runner = new Runner(baseOpts).runSingle();
Result baseResult = runner.getPrimaryResult();
// Printing a nice table...
System.out.println("---------------------------------------");
System.out.printf("Baseline score: %10.2f %s%n",
baseResult.getScore(),
baseResult.getScoreUnit()
);
for (Chromosome c : pop.getAll()) {
System.out.printf("%10.2f %s (%+10.2f%%) %s%n",
c.getScore(),
baseResult.getScoreUnit(),
(c.getScore() / baseResult.getScore() - 1) * 100,
c.toString()
);
}
System.out.println();
Population newPop = new Population();
// Copy out elite solutions
final int ELITE = 2;
for (Chromosome c : pop.getAll().subList(0, ELITE)) {
newPop.addChromosome(c);
}
// Cross-breed the rest of new population
while (newPop.size() < pop.size()) {
Chromosome p1 = pop.selectToBreed();
Chromosome p2 = pop.selectToBreed();
newPop.addChromosome(p1.crossover(p2).mutate());
newPop.addChromosome(p2.crossover(p1).mutate());
}
pop = newPop;
}
}
/**
* Population.
*/
public static class Population {
private final List<Chromosome> list = new ArrayList<>();
public void addChromosome(Chromosome c) {
list.add(c);
Collections.sort(list);
}
/**
* Select the breeding material.
* Solutions with better score have better chance to be selected.
* @return breed
*/
public Chromosome selectToBreed() {
double totalScore = 0D;
for (Chromosome c : list) {
totalScore += c.score();
}
double thresh = Math.random() * totalScore;
for (Chromosome c : list) {
if (thresh >= 0) {
thresh -= c.score();
} else {
return c;
}
}
// Return the last
return list.get(list.size() - 1);
}
public int size() {
return list.size();
}
public List<Chromosome> getAll() {
return list;
}
}
/**
* Chromosome: encodes solution.
*/
public static class Chromosome implements Comparable<Chromosome> {
// Current score is not yet computed.
double score = Double.NEGATIVE_INFINITY;
// Base options to mix in
final Options baseOpts;
// These are current HotSpot defaults.
int freqInlineSize = 325;
int inlineSmallCode = 1000;
int maxInlineLevel = 9;
int maxInlineSize = 35;
int maxRecursiveInlineLevel = 1;
int minInliningThreshold = 250;
public Chromosome(Options baseOpts) {
this.baseOpts = baseOpts;
}
public double score() {
if (score != Double.NEGATIVE_INFINITY) {
// Already got the score, shortcutting
return score;
}
try {
// Add the options encoded by this solution:
// a) Mix in base options.
// b) Add JVM arguments: we opt to parse the
// stringly representation to make the example
// shorter. There are, of course, cleaner ways
// to do this.
Options theseOpts = new OptionsBuilder()
.parent(baseOpts)
.jvmArgs(toString().split("[ ]"))
.build();
// Run through JMH and get the result back.
RunResult runResult = new Runner(theseOpts).runSingle();
score = runResult.getPrimaryResult().getScore();
} catch (RunnerException e) {
// Something went wrong, the solution is defective
score = Double.MIN_VALUE;
}
return score;
}
@Override
public int compareTo(Chromosome o) {
// Order by score, descending.
return -Double.compare(score(), o.score());
}
@Override
public String toString() {
return "-XX:FreqInlineSize=" + freqInlineSize +
" -XX:InlineSmallCode=" + inlineSmallCode +
" -XX:MaxInlineLevel=" + maxInlineLevel +
" -XX:MaxInlineSize=" + maxInlineSize +
" -XX:MaxRecursiveInlineLevel=" + maxRecursiveInlineLevel +
" -XX:MinInliningThreshold=" + minInliningThreshold;
}
public Chromosome crossover(Chromosome other) {
// Perform crossover:
// While this is a very naive way to perform crossover, it still works.
final double CROSSOVER_PROB = 0.1;
Chromosome result = new Chromosome(baseOpts);
result.freqInlineSize = (Math.random() < CROSSOVER_PROB) ?
this.freqInlineSize : other.freqInlineSize;
result.inlineSmallCode = (Math.random() < CROSSOVER_PROB) ?
this.inlineSmallCode : other.inlineSmallCode;
result.maxInlineLevel = (Math.random() < CROSSOVER_PROB) ?
this.maxInlineLevel : other.maxInlineLevel;
result.maxInlineSize = (Math.random() < CROSSOVER_PROB) ?
this.maxInlineSize : other.maxInlineSize;
result.maxRecursiveInlineLevel = (Math.random() < CROSSOVER_PROB) ?
this.maxRecursiveInlineLevel : other.maxRecursiveInlineLevel;
result.minInliningThreshold = (Math.random() < CROSSOVER_PROB) ?
this.minInliningThreshold : other.minInliningThreshold;
return result;
}
public Chromosome mutate() {
// Perform mutation:
// Again, this is a naive way to do mutation, but it still works.
Chromosome result = new Chromosome(baseOpts);
result.freqInlineSize = (int) randomChange(freqInlineSize);
result.inlineSmallCode = (int) randomChange(inlineSmallCode);
result.maxInlineLevel = (int) randomChange(maxInlineLevel);
result.maxInlineSize = (int) randomChange(maxInlineSize);
result.maxRecursiveInlineLevel = (int) randomChange(maxRecursiveInlineLevel);
result.minInliningThreshold = (int) randomChange(minInliningThreshold);
return result;
}
private double randomChange(double v) {
final double MUTATE_PROB = 0.5;
if (Math.random() < MUTATE_PROB) {
if (Math.random() < 0.5) {
return v / (Math.random() * 2);
} else {
return v * (Math.random() * 2);
}
} else {
return v;
}
}
public double getScore() {
return score;
}
}
}
| 12,133 | 35.005935 | 89 | java |
jmh | jmh-master/jmh-samples/src/main/java/org/openjdk/jmh/samples/JMHSample_26_BatchSize.java | /*
* Copyright (c) 2014, Oracle America, Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* * Neither the name of Oracle nor the names of its contributors may be used
* to endorse or promote products derived from this software without
* specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
* THE POSSIBILITY OF SUCH DAMAGE.
*/
package org.openjdk.jmh.samples;
import org.openjdk.jmh.annotations.Benchmark;
import org.openjdk.jmh.annotations.BenchmarkMode;
import org.openjdk.jmh.annotations.Level;
import org.openjdk.jmh.annotations.Measurement;
import org.openjdk.jmh.annotations.Mode;
import org.openjdk.jmh.annotations.Scope;
import org.openjdk.jmh.annotations.Setup;
import org.openjdk.jmh.annotations.State;
import org.openjdk.jmh.annotations.Warmup;
import org.openjdk.jmh.runner.Runner;
import org.openjdk.jmh.runner.RunnerException;
import org.openjdk.jmh.runner.options.Options;
import org.openjdk.jmh.runner.options.OptionsBuilder;
import java.util.LinkedList;
import java.util.List;
@State(Scope.Thread)
public class JMHSample_26_BatchSize {
/*
* Sometimes you need to evaluate operation which doesn't have
* the steady state. The cost of a benchmarked operation may
* significantly vary from invocation to invocation.
*
* In this case, using the timed measurements is not a good idea,
* and the only acceptable benchmark mode is a single shot. On the
* other hand, the operation may be too small for reliable single
* shot measurement.
*
* We can use "batch size" parameter to describe the number of
* @Benchmark invocations to do per one "shot" without looping the method
* manually and protect from problems described in JMHSample_11_Loops.
* If there are any @Setup/@TearDown(Level.Invocation), they still run
* per each @Benchmark invocation.
*/
/*
* Suppose we want to measure insertion in the middle of the list.
*/
List<String> list = new LinkedList<>();
@Benchmark
@Warmup(iterations = 5, time = 1)
@Measurement(iterations = 5, time = 1)
@BenchmarkMode(Mode.AverageTime)
public List<String> measureWrong_1() {
list.add(list.size() / 2, "something");
return list;
}
@Benchmark
@Warmup(iterations = 5, time = 5)
@Measurement(iterations = 5, time = 5)
@BenchmarkMode(Mode.AverageTime)
public List<String> measureWrong_5() {
list.add(list.size() / 2, "something");
return list;
}
/*
* This is what you do with JMH.
*/
@Benchmark
@Warmup(iterations = 5, batchSize = 5000)
@Measurement(iterations = 5, batchSize = 5000)
@BenchmarkMode(Mode.SingleShotTime)
public List<String> measureRight() {
list.add(list.size() / 2, "something");
return list;
}
@Setup(Level.Iteration)
public void setup(){
list.clear();
}
/*
* ============================== HOW TO RUN THIS TEST: ====================================
*
* You can see completely different results for measureWrong_1 and measureWrong_5; this
* is because the workload has no steady state. The result of the workload is dependent
* on the measurement time. measureRight does not have this drawback, because it measures
* the N invocations of the test method and measures it's time.
*
* We measure batch of 5000 invocations and consider the batch as the single operation.
*
* You can run this test:
*
* a) Via the command line:
* $ mvn clean install
* $ java -jar target/benchmarks.jar JMHSample_26 -f 1
*
* b) Via the Java API:
* (see the JMH homepage for possible caveats when running from IDE:
* http://openjdk.java.net/projects/code-tools/jmh/)
*/
public static void main(String[] args) throws RunnerException {
Options opt = new OptionsBuilder()
.include(JMHSample_26_BatchSize.class.getSimpleName())
.forks(1)
.build();
new Runner(opt).run();
}
}
| 5,317 | 36.450704 | 96 | java |
jmh | jmh-master/jmh-samples/src/main/java/org/openjdk/jmh/samples/JMHSample_27_Params.java | /*
* Copyright (c) 2014, Oracle America, Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* * Neither the name of Oracle nor the names of its contributors may be used
* to endorse or promote products derived from this software without
* specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
* THE POSSIBILITY OF SUCH DAMAGE.
*/
package org.openjdk.jmh.samples;
import org.openjdk.jmh.annotations.Benchmark;
import org.openjdk.jmh.annotations.BenchmarkMode;
import org.openjdk.jmh.annotations.Fork;
import org.openjdk.jmh.annotations.Measurement;
import org.openjdk.jmh.annotations.Mode;
import org.openjdk.jmh.annotations.OutputTimeUnit;
import org.openjdk.jmh.annotations.Param;
import org.openjdk.jmh.annotations.Scope;
import org.openjdk.jmh.annotations.State;
import org.openjdk.jmh.annotations.Warmup;
import org.openjdk.jmh.runner.Runner;
import org.openjdk.jmh.runner.RunnerException;
import org.openjdk.jmh.runner.options.Options;
import org.openjdk.jmh.runner.options.OptionsBuilder;
import java.math.BigInteger;
import java.util.concurrent.TimeUnit;
@BenchmarkMode(Mode.AverageTime)
@OutputTimeUnit(TimeUnit.NANOSECONDS)
@Warmup(iterations = 5, time = 1, timeUnit = TimeUnit.SECONDS)
@Measurement(iterations = 5, time = 1, timeUnit = TimeUnit.SECONDS)
@Fork(1)
@State(Scope.Benchmark)
public class JMHSample_27_Params {
/**
* In many cases, the experiments require walking the configuration space
* for a benchmark. This is needed for additional control, or investigating
* how the workload performance changes with different settings.
*/
@Param({"1", "31", "65", "101", "103"})
public int arg;
@Param({"0", "1", "2", "4", "8", "16", "32"})
public int certainty;
@Benchmark
public boolean bench() {
return BigInteger.valueOf(arg).isProbablePrime(certainty);
}
/*
* ============================== HOW TO RUN THIS TEST: ====================================
*
* Note the performance is different with different parameters.
*
* You can run this test:
*
* a) Via the command line:
* $ mvn clean install
* $ java -jar target/benchmarks.jar JMHSample_27
*
* You can juggle parameters through the command line, e.g. with "-p arg=41,42"
*
* b) Via the Java API:
* (see the JMH homepage for possible caveats when running from IDE:
* http://openjdk.java.net/projects/code-tools/jmh/)
*/
public static void main(String[] args) throws RunnerException {
Options opt = new OptionsBuilder()
.include(JMHSample_27_Params.class.getSimpleName())
// .param("arg", "41", "42") // Use this to selectively constrain/override parameters
.build();
new Runner(opt).run();
}
}
| 4,053 | 37.980769 | 100 | java |
jmh | jmh-master/jmh-samples/src/main/java/org/openjdk/jmh/samples/JMHSample_28_BlackholeHelpers.java | /*
* Copyright (c) 2014, Oracle America, Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* * Neither the name of Oracle nor the names of its contributors may be used
* to endorse or promote products derived from this software without
* specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
* THE POSSIBILITY OF SUCH DAMAGE.
*/
package org.openjdk.jmh.samples;
import org.openjdk.jmh.annotations.Benchmark;
import org.openjdk.jmh.annotations.BenchmarkMode;
import org.openjdk.jmh.annotations.Fork;
import org.openjdk.jmh.annotations.Measurement;
import org.openjdk.jmh.annotations.Mode;
import org.openjdk.jmh.annotations.OutputTimeUnit;
import org.openjdk.jmh.annotations.Scope;
import org.openjdk.jmh.annotations.Setup;
import org.openjdk.jmh.annotations.State;
import org.openjdk.jmh.annotations.Warmup;
import org.openjdk.jmh.infra.Blackhole;
import org.openjdk.jmh.runner.Runner;
import org.openjdk.jmh.runner.RunnerException;
import org.openjdk.jmh.runner.options.Options;
import org.openjdk.jmh.runner.options.OptionsBuilder;
import java.util.concurrent.TimeUnit;
@BenchmarkMode(Mode.AverageTime)
@OutputTimeUnit(TimeUnit.NANOSECONDS)
@Warmup(iterations = 5, time = 1, timeUnit = TimeUnit.SECONDS)
@Measurement(iterations = 5, time = 1, timeUnit = TimeUnit.SECONDS)
@Fork(1)
@State(Scope.Thread)
public class JMHSample_28_BlackholeHelpers {
/**
* Sometimes you need the black hole not in @Benchmark method, but in
* helper methods, because you want to pass it through to the concrete
* implementation which is instantiated in helper methods. In this case,
* you can request the black hole straight in the helper method signature.
* This applies to both @Setup and @TearDown methods, and also to other
* JMH infrastructure objects, like Control.
*
* Below is the variant of {@link org.openjdk.jmh.samples.JMHSample_08_DeadCode}
* test, but wrapped in the anonymous classes.
*/
public interface Worker {
void work();
}
private Worker workerBaseline;
private Worker workerRight;
private Worker workerWrong;
private double compute(double d) {
for (int c = 0; c < 10; c++) {
d = d * d / Math.PI;
}
return d;
}
@Setup
public void setup(final Blackhole bh) {
workerBaseline = new Worker() {
double x;
@Override
public void work() {
// do nothing
}
};
workerWrong = new Worker() {
double x;
@Override
public void work() {
compute(x);
}
};
workerRight = new Worker() {
double x;
@Override
public void work() {
bh.consume(compute(x));
}
};
}
@Benchmark
public void baseline() {
workerBaseline.work();
}
@Benchmark
public void measureWrong() {
workerWrong.work();
}
@Benchmark
public void measureRight() {
workerRight.work();
}
/*
* ============================== HOW TO RUN THIS TEST: ====================================
*
* You will see measureWrong() running on-par with baseline().
* Both measureRight() are measuring twice the baseline, so the logs are intact.
*
* You can run this test:
*
* a) Via the command line:
* $ mvn clean install
* $ java -jar target/benchmarks.jar JMHSample_28
*
* b) Via the Java API:
* (see the JMH homepage for possible caveats when running from IDE:
* http://openjdk.java.net/projects/code-tools/jmh/)
*/
public static void main(String[] args) throws RunnerException {
Options opt = new OptionsBuilder()
.include(JMHSample_28_BlackholeHelpers.class.getSimpleName())
.build();
new Runner(opt).run();
}
}
| 5,194 | 31.879747 | 96 | java |
jmh | jmh-master/jmh-samples/src/main/java/org/openjdk/jmh/samples/JMHSample_29_StatesDAG.java | /*
* Copyright (c) 2014, Oracle America, Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* * Neither the name of Oracle nor the names of its contributors may be used
* to endorse or promote products derived from this software without
* specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
* THE POSSIBILITY OF SUCH DAMAGE.
*/
package org.openjdk.jmh.samples;
import org.openjdk.jmh.annotations.Benchmark;
import org.openjdk.jmh.annotations.BenchmarkMode;
import org.openjdk.jmh.annotations.Fork;
import org.openjdk.jmh.annotations.Measurement;
import org.openjdk.jmh.annotations.Mode;
import org.openjdk.jmh.annotations.OutputTimeUnit;
import org.openjdk.jmh.annotations.Scope;
import org.openjdk.jmh.annotations.Setup;
import org.openjdk.jmh.annotations.State;
import org.openjdk.jmh.annotations.TearDown;
import org.openjdk.jmh.annotations.Warmup;
import org.openjdk.jmh.runner.Runner;
import org.openjdk.jmh.runner.RunnerException;
import org.openjdk.jmh.runner.options.Options;
import org.openjdk.jmh.runner.options.OptionsBuilder;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;
import java.util.concurrent.TimeUnit;
@BenchmarkMode(Mode.AverageTime)
@OutputTimeUnit(TimeUnit.NANOSECONDS)
@Warmup(iterations = 5, time = 1, timeUnit = TimeUnit.SECONDS)
@Measurement(iterations = 5, time = 1, timeUnit = TimeUnit.SECONDS)
@Fork(1)
@State(Scope.Thread)
public class JMHSample_29_StatesDAG {
/**
* WARNING:
* THIS IS AN EXPERIMENTAL FEATURE, BE READY FOR IT BECOME REMOVED WITHOUT NOTICE!
*/
/**
* There are weird cases when the benchmark state is more cleanly described
* by the set of @States, and those @States reference each other. JMH allows
* linking @States in directed acyclic graphs (DAGs) by referencing @States
* in helper method signatures. (Note that {@link org.openjdk.jmh.samples.JMHSample_28_BlackholeHelpers}
* is just a special case of that.
*
* Following the interface for @Benchmark calls, all @Setups for
* referenced @State-s are fired before it becomes accessible to current @State.
* Similarly, no @TearDown methods are fired for referenced @State before
* current @State is done with it.
*/
/*
* This is a model case, and it might not be a good benchmark.
* // TODO: Replace it with the benchmark which does something useful.
*/
public static class Counter {
int x;
public int inc() {
return x++;
}
public void dispose() {
// pretend this is something really useful
}
}
/*
* Shared state maintains the set of Counters, and worker threads should
* poll their own instances of Counter to work with. However, it should only
* be done once, and therefore, Local state caches it after requesting the
* counter from Shared state.
*/
@State(Scope.Benchmark)
public static class Shared {
List<Counter> all;
Queue<Counter> available;
@Setup
public synchronized void setup() {
all = new ArrayList<>();
for (int c = 0; c < 10; c++) {
all.add(new Counter());
}
available = new LinkedList<>();
available.addAll(all);
}
@TearDown
public synchronized void tearDown() {
for (Counter c : all) {
c.dispose();
}
}
public synchronized Counter getMine() {
return available.poll();
}
}
@State(Scope.Thread)
public static class Local {
Counter cnt;
@Setup
public void setup(Shared shared) {
cnt = shared.getMine();
}
}
@Benchmark
public int test(Local local) {
return local.cnt.inc();
}
/*
* ============================== HOW TO RUN THIS TEST: ====================================
*
* You can run this test:
*
* a) Via the command line:
* $ mvn clean install
* $ java -jar target/benchmarks.jar JMHSample_29
*
* b) Via the Java API:
* (see the JMH homepage for possible caveats when running from IDE:
* http://openjdk.java.net/projects/code-tools/jmh/)
*/
public static void main(String[] args) throws RunnerException {
Options opt = new OptionsBuilder()
.include(JMHSample_29_StatesDAG.class.getSimpleName())
.build();
new Runner(opt).run();
}
}
| 5,809 | 32.77907 | 108 | java |
jmh | jmh-master/jmh-samples/src/main/java/org/openjdk/jmh/samples/JMHSample_30_Interrupts.java | /*
* Copyright (c) 2014, Oracle America, Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* * Neither the name of Oracle nor the names of its contributors may be used
* to endorse or promote products derived from this software without
* specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
* THE POSSIBILITY OF SUCH DAMAGE.
*/
package org.openjdk.jmh.samples;
import org.openjdk.jmh.annotations.Benchmark;
import org.openjdk.jmh.annotations.BenchmarkMode;
import org.openjdk.jmh.annotations.Group;
import org.openjdk.jmh.annotations.Mode;
import org.openjdk.jmh.annotations.OutputTimeUnit;
import org.openjdk.jmh.annotations.Scope;
import org.openjdk.jmh.annotations.Setup;
import org.openjdk.jmh.annotations.State;
import org.openjdk.jmh.runner.Runner;
import org.openjdk.jmh.runner.RunnerException;
import org.openjdk.jmh.runner.options.Options;
import org.openjdk.jmh.runner.options.OptionsBuilder;
import org.openjdk.jmh.runner.options.TimeValue;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.TimeUnit;
@BenchmarkMode(Mode.AverageTime)
@OutputTimeUnit(TimeUnit.NANOSECONDS)
@State(Scope.Group)
public class JMHSample_30_Interrupts {
/*
* JMH can also detect when threads are stuck in the benchmarks, and try
* to forcefully interrupt the benchmark thread. JMH tries to do that
* when it is arguably sure it would not affect the measurement.
*/
/*
* In this example, we want to measure the simple performance characteristics
* of the ArrayBlockingQueue. Unfortunately, doing that without a harness
* support will deadlock one of the threads, because the executions of
* take/put are not paired perfectly. Fortunately for us, both methods react
* to interrupts well, and therefore we can rely on JMH to terminate the
* measurement for us. JMH will notify users about the interrupt actions
* nevertheless, so users can see if those interrupts affected the measurement.
* JMH will start issuing interrupts after the default or user-specified timeout
* had been reached.
*
* This is a variant of org.openjdk.jmh.samples.JMHSample_18_Control, but without
* the explicit control objects. This example is suitable for the methods which
* react to interrupts gracefully.
*/
private BlockingQueue<Integer> q;
@Setup
public void setup() {
q = new ArrayBlockingQueue<>(1);
}
@Group("Q")
@Benchmark
public Integer take() throws InterruptedException {
return q.take();
}
@Group("Q")
@Benchmark
public void put() throws InterruptedException {
q.put(42);
}
/*
* ============================== HOW TO RUN THIS TEST: ====================================
*
* You can run this test:
*
* a) Via the command line:
* $ mvn clean install
* $ java -jar target/benchmarks.jar JMHSample_30 -t 2 -f 5 -to 10
* (we requested 2 threads, 5 forks, and 10 sec timeout)
*
* b) Via the Java API:
* (see the JMH homepage for possible caveats when running from IDE:
* http://openjdk.java.net/projects/code-tools/jmh/)
*/
public static void main(String[] args) throws RunnerException {
Options opt = new OptionsBuilder()
.include(JMHSample_30_Interrupts.class.getSimpleName())
.threads(2)
.forks(5)
.timeout(TimeValue.seconds(10))
.build();
new Runner(opt).run();
}
}
| 4,831 | 37.967742 | 96 | java |
jmh | jmh-master/jmh-samples/src/main/java/org/openjdk/jmh/samples/JMHSample_31_InfraParams.java | /*
* Copyright (c) 2014, Oracle America, Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* * Neither the name of Oracle nor the names of its contributors may be used
* to endorse or promote products derived from this software without
* specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
* THE POSSIBILITY OF SUCH DAMAGE.
*/
package org.openjdk.jmh.samples;
import org.openjdk.jmh.annotations.Benchmark;
import org.openjdk.jmh.annotations.BenchmarkMode;
import org.openjdk.jmh.annotations.Mode;
import org.openjdk.jmh.annotations.OutputTimeUnit;
import org.openjdk.jmh.annotations.Scope;
import org.openjdk.jmh.annotations.Setup;
import org.openjdk.jmh.annotations.State;
import org.openjdk.jmh.infra.BenchmarkParams;
import org.openjdk.jmh.infra.ThreadParams;
import org.openjdk.jmh.runner.Runner;
import org.openjdk.jmh.runner.RunnerException;
import org.openjdk.jmh.runner.options.Options;
import org.openjdk.jmh.runner.options.OptionsBuilder;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.TimeUnit;
@BenchmarkMode(Mode.Throughput)
@OutputTimeUnit(TimeUnit.SECONDS)
@State(Scope.Benchmark)
public class JMHSample_31_InfraParams {
/*
* There is a way to query JMH about the current running mode. This is
* possible with three infrastructure objects we can request to be injected:
* - BenchmarkParams: covers the benchmark-global configuration
* - IterationParams: covers the current iteration configuration
* - ThreadParams: covers the specifics about threading
*
* Suppose we want to check how the ConcurrentHashMap scales under different
* parallelism levels. We can put concurrencyLevel in @Param, but it sometimes
* inconvenient if, say, we want it to follow the @Threads count. Here is
* how we can query JMH about how many threads was requested for the current run,
* and put that into concurrencyLevel argument for CHM constructor.
*/
static final int THREAD_SLICE = 1000;
private ConcurrentHashMap<String, String> mapSingle;
private ConcurrentHashMap<String, String> mapFollowThreads;
@Setup
public void setup(BenchmarkParams params) {
int capacity = 16 * THREAD_SLICE * params.getThreads();
mapSingle = new ConcurrentHashMap<>(capacity, 0.75f, 1);
mapFollowThreads = new ConcurrentHashMap<>(capacity, 0.75f, params.getThreads());
}
/*
* Here is another neat trick. Generate the distinct set of keys for all threads:
*/
@State(Scope.Thread)
public static class Ids {
private List<String> ids;
@Setup
public void setup(ThreadParams threads) {
ids = new ArrayList<>();
for (int c = 0; c < THREAD_SLICE; c++) {
ids.add("ID" + (THREAD_SLICE * threads.getThreadIndex() + c));
}
}
}
@Benchmark
public void measureDefault(Ids ids) {
for (String s : ids.ids) {
mapSingle.remove(s);
mapSingle.put(s, s);
}
}
@Benchmark
public void measureFollowThreads(Ids ids) {
for (String s : ids.ids) {
mapFollowThreads.remove(s);
mapFollowThreads.put(s, s);
}
}
/*
* ============================== HOW TO RUN THIS TEST: ====================================
*
* You can run this test:
*
* a) Via the command line:
* $ mvn clean install
* $ java -jar target/benchmarks.jar JMHSample_31 -t 4 -f 5
* (we requested 4 threads, and 5 forks; there are also other options, see -h)
*
* b) Via the Java API:
* (see the JMH homepage for possible caveats when running from IDE:
* http://openjdk.java.net/projects/code-tools/jmh/)
*/
public static void main(String[] args) throws RunnerException {
Options opt = new OptionsBuilder()
.include(JMHSample_31_InfraParams.class.getSimpleName())
.threads(4)
.forks(5)
.build();
new Runner(opt).run();
}
}
| 5,386 | 36.93662 | 96 | java |
jmh | jmh-master/jmh-samples/src/main/java/org/openjdk/jmh/samples/JMHSample_32_BulkWarmup.java | /*
* Copyright (c) 2014, Oracle America, Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* * Neither the name of Oracle nor the names of its contributors may be used
* to endorse or promote products derived from this software without
* specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
* THE POSSIBILITY OF SUCH DAMAGE.
*/
package org.openjdk.jmh.samples;
import org.openjdk.jmh.annotations.Benchmark;
import org.openjdk.jmh.annotations.BenchmarkMode;
import org.openjdk.jmh.annotations.CompilerControl;
import org.openjdk.jmh.annotations.Mode;
import org.openjdk.jmh.annotations.OutputTimeUnit;
import org.openjdk.jmh.annotations.Scope;
import org.openjdk.jmh.annotations.State;
import org.openjdk.jmh.runner.Runner;
import org.openjdk.jmh.runner.RunnerException;
import org.openjdk.jmh.runner.options.Options;
import org.openjdk.jmh.runner.options.OptionsBuilder;
import org.openjdk.jmh.runner.options.WarmupMode;
import java.util.concurrent.TimeUnit;
@State(Scope.Thread)
@BenchmarkMode(Mode.AverageTime)
@OutputTimeUnit(TimeUnit.NANOSECONDS)
public class JMHSample_32_BulkWarmup {
/*
* This is an addendum to JMHSample_12_Forking test.
*
* Sometimes you want an opposite configuration: instead of separating the profiles
* for different benchmarks, you want to mix them together to test the worst-case
* scenario.
*
* JMH has a bulk warmup feature for that: it does the warmups for all the tests
* first, and then measures them. JMH still forks the JVM for each test, but once the
* new JVM has started, all the warmups are being run there, before running the
* measurement. This helps to dodge the type profile skews, as each test is still
* executed in a different JVM, and we only "mix" the warmup code we want.
*/
/*
* These test classes are borrowed verbatim from JMHSample_12_Forking.
*/
public interface Counter {
int inc();
}
public static class Counter1 implements Counter {
private int x;
@Override
public int inc() {
return x++;
}
}
public static class Counter2 implements Counter {
private int x;
@Override
public int inc() {
return x++;
}
}
Counter c1 = new Counter1();
Counter c2 = new Counter2();
/*
* And this is our test payload. Notice we have to break the inlining of the payload,
* so that in could not be inlined in either measure_c1() or measure_c2() below, and
* specialized for that only call.
*/
@CompilerControl(CompilerControl.Mode.DONT_INLINE)
public int measure(Counter c) {
int s = 0;
for (int i = 0; i < 10; i++) {
s += c.inc();
}
return s;
}
@Benchmark
public int measure_c1() {
return measure(c1);
}
@Benchmark
public int measure_c2() {
return measure(c2);
}
/*
* ============================== HOW TO RUN THIS TEST: ====================================
*
* Note how JMH runs the warmups first, and only then a given test. Note how JMH re-warmups
* the JVM for each test. The scores for C1 and C2 cases are equally bad, compare them to
* the scores from JMHSample_12_Forking.
*
* You can run this test:
*
* a) Via the command line:
* $ mvn clean install
* $ java -jar target/benchmarks.jar JMHSample_32 -f 1 -wm BULK
* (we requested a single fork, and bulk warmup mode; there are also other options, see -h)
*
* b) Via the Java API:
* (see the JMH homepage for possible caveats when running from IDE:
* http://openjdk.java.net/projects/code-tools/jmh/)
*/
public static void main(String[] args) throws RunnerException {
Options opt = new OptionsBuilder()
.include(JMHSample_32_BulkWarmup.class.getSimpleName())
// .includeWarmup(...) <-- this may include other benchmarks into warmup
.warmupMode(WarmupMode.BULK) // see other WarmupMode.* as well
.forks(1)
.build();
new Runner(opt).run();
}
}
| 5,441 | 34.802632 | 98 | java |
jmh | jmh-master/jmh-samples/src/main/java/org/openjdk/jmh/samples/JMHSample_33_SecurityManager.java | /*
* Copyright (c) 2014, Oracle America, Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* * Neither the name of Oracle nor the names of its contributors may be used
* to endorse or promote products derived from this software without
* specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
* THE POSSIBILITY OF SUCH DAMAGE.
*/
package org.openjdk.jmh.samples;
import org.openjdk.jmh.annotations.Benchmark;
import org.openjdk.jmh.annotations.BenchmarkMode;
import org.openjdk.jmh.annotations.Mode;
import org.openjdk.jmh.annotations.OutputTimeUnit;
import org.openjdk.jmh.annotations.Scope;
import org.openjdk.jmh.annotations.Setup;
import org.openjdk.jmh.annotations.State;
import org.openjdk.jmh.annotations.TearDown;
import org.openjdk.jmh.runner.Runner;
import org.openjdk.jmh.runner.RunnerException;
import org.openjdk.jmh.runner.options.Options;
import org.openjdk.jmh.runner.options.OptionsBuilder;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.security.NoSuchAlgorithmException;
import java.security.Policy;
import java.security.URIParameter;
import java.util.concurrent.TimeUnit;
@BenchmarkMode(Mode.AverageTime)
@OutputTimeUnit(TimeUnit.NANOSECONDS)
public class JMHSample_33_SecurityManager {
/*
* Some targeted tests may care about SecurityManager being installed.
* Since JMH itself needs to do privileged actions, it is not enough
* to blindly install the SecurityManager, as JMH infrastructure will fail.
*/
/*
* In this example, we want to measure the performance of System.getProperty
* with SecurityManager installed or not. To do this, we have two state classes
* with helper methods. One that reads the default JMH security policy (we ship one
* with JMH), and installs the security manager; another one that makes sure
* the SecurityManager is not installed.
*
* If you need a restricted security policy for the tests, you are advised to
* get /jmh-security-minimal.policy, that contains the minimal permissions
* required for JMH benchmark to run, merge the new permissions there, produce new
* policy file in a temporary location, and load that policy file instead.
* There is also /jmh-security-minimal-runner.policy, that contains the minimal
* permissions for the JMH harness to run, if you want to use JVM args to arm
* the SecurityManager.
*/
@State(Scope.Benchmark)
public static class SecurityManagerInstalled {
@Setup
public void setup() throws IOException, NoSuchAlgorithmException, URISyntaxException {
URI policyFile = JMHSample_33_SecurityManager.class.getResource("/jmh-security.policy").toURI();
Policy.setPolicy(Policy.getInstance("JavaPolicy", new URIParameter(policyFile)));
System.setSecurityManager(new SecurityManager());
}
@TearDown
public void tearDown() {
System.setSecurityManager(null);
}
}
@State(Scope.Benchmark)
public static class SecurityManagerEmpty {
@Setup
public void setup() throws IOException, NoSuchAlgorithmException, URISyntaxException {
System.setSecurityManager(null);
}
}
@Benchmark
public String testWithSM(SecurityManagerInstalled s) throws InterruptedException {
return System.getProperty("java.home");
}
@Benchmark
public String testWithoutSM(SecurityManagerEmpty s) throws InterruptedException {
return System.getProperty("java.home");
}
/*
* ============================== HOW TO RUN THIS TEST: ====================================
*
* You can run this test:
*
* a) Via the command line:
* $ mvn clean install
* $ java -jar target/benchmarks.jar JMHSample_33 -f 1
* (we requested 5 warmup iterations, 5 forks; there are also other options, see -h))
*
* b) Via the Java API:
* (see the JMH homepage for possible caveats when running from IDE:
* http://openjdk.java.net/projects/code-tools/jmh/)
*/
public static void main(String[] args) throws RunnerException {
Options opt = new OptionsBuilder()
.include(JMHSample_33_SecurityManager.class.getSimpleName())
.warmupIterations(5)
.measurementIterations(5)
.forks(1)
.build();
new Runner(opt).run();
}
}
| 5,721 | 39.871429 | 108 | java |
jmh | jmh-master/jmh-samples/src/main/java/org/openjdk/jmh/samples/JMHSample_34_SafeLooping.java | /*
* Copyright (c) 2014, Oracle America, Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* * Neither the name of Oracle nor the names of its contributors may be used
* to endorse or promote products derived from this software without
* specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
* THE POSSIBILITY OF SUCH DAMAGE.
*/
package org.openjdk.jmh.samples;
import org.openjdk.jmh.annotations.Benchmark;
import org.openjdk.jmh.annotations.BenchmarkMode;
import org.openjdk.jmh.annotations.CompilerControl;
import org.openjdk.jmh.annotations.Fork;
import org.openjdk.jmh.annotations.Measurement;
import org.openjdk.jmh.annotations.Mode;
import org.openjdk.jmh.annotations.OutputTimeUnit;
import org.openjdk.jmh.annotations.Param;
import org.openjdk.jmh.annotations.Scope;
import org.openjdk.jmh.annotations.Setup;
import org.openjdk.jmh.annotations.State;
import org.openjdk.jmh.annotations.Warmup;
import org.openjdk.jmh.infra.Blackhole;
import org.openjdk.jmh.runner.Runner;
import org.openjdk.jmh.runner.RunnerException;
import org.openjdk.jmh.runner.options.Options;
import org.openjdk.jmh.runner.options.OptionsBuilder;
import java.util.concurrent.TimeUnit;
@State(Scope.Thread)
@Warmup(iterations = 5, time = 1, timeUnit = TimeUnit.SECONDS)
@Measurement(iterations = 5, time = 1, timeUnit = TimeUnit.SECONDS)
@Fork(3)
@BenchmarkMode(Mode.AverageTime)
@OutputTimeUnit(TimeUnit.NANOSECONDS)
public class JMHSample_34_SafeLooping {
/*
* JMHSample_11_Loops warns about the dangers of using loops in @Benchmark methods.
* Sometimes, however, one needs to traverse through several elements in a dataset.
* This is hard to do without loops, and therefore we need to devise a scheme for
* safe looping.
*/
/*
* Suppose we want to measure how much it takes to execute work() with different
* arguments. This mimics a frequent use case when multiple instances with the same
* implementation, but different data, is measured.
*/
static final int BASE = 42;
static int work(int x) {
return BASE + x;
}
/*
* Every benchmark requires control. We do a trivial control for our benchmarks
* by checking the benchmark costs are growing linearly with increased task size.
* If it doesn't, then something wrong is happening.
*/
@Param({"1", "10", "100", "1000"})
int size;
int[] xs;
@Setup
public void setup() {
xs = new int[size];
for (int c = 0; c < size; c++) {
xs[c] = c;
}
}
/*
* First, the obviously wrong way: "saving" the result into a local variable would not
* work. A sufficiently smart compiler will inline work(), and figure out only the last
* work() call needs to be evaluated. Indeed, if you run it with varying $size, the score
* will stay the same!
*/
@Benchmark
public int measureWrong_1() {
int acc = 0;
for (int x : xs) {
acc = work(x);
}
return acc;
}
/*
* Second, another wrong way: "accumulating" the result into a local variable. While
* it would force the computation of each work() method, there are software pipelining
* effects in action, that can merge the operations between two otherwise distinct work()
* bodies. This will obliterate the benchmark setup.
*
* In this example, HotSpot does the unrolled loop, merges the $BASE operands into a single
* addition to $acc, and then does a bunch of very tight stores of $x-s. The final performance
* depends on how much of the loop unrolling happened *and* how much data is available to make
* the large strides.
*/
@Benchmark
public int measureWrong_2() {
int acc = 0;
for (int x : xs) {
acc += work(x);
}
return acc;
}
/*
* Now, let's see how to measure these things properly. A very straight-forward way to
* break the merging is to sink each result to Blackhole. This will force runtime to compute
* every work() call in full. (We would normally like to care about several concurrent work()
* computations at once, but the memory effects from Blackhole.consume() prevent those optimization
* on most runtimes).
*/
@Benchmark
public void measureRight_1(Blackhole bh) {
for (int x : xs) {
bh.consume(work(x));
}
}
/*
* DANGEROUS AREA, PLEASE READ THE DESCRIPTION BELOW.
*
* Sometimes, the cost of sinking the value into a Blackhole is dominating the nano-benchmark score.
* In these cases, one may try to do a make-shift "sinker" with non-inlineable method. This trick is
* *very* VM-specific, and can only be used if you are verifying the generated code (that's a good
* strategy when dealing with nano-benchmarks anyway).
*
* You SHOULD NOT use this trick in most cases. Apply only where needed.
*/
@Benchmark
public void measureRight_2() {
for (int x : xs) {
sink(work(x));
}
}
@CompilerControl(CompilerControl.Mode.DONT_INLINE)
public static void sink(int v) {
// IT IS VERY IMPORTANT TO MATCH THE SIGNATURE TO AVOID AUTOBOXING.
// The method intentionally does nothing.
}
/*
* ============================== HOW TO RUN THIS TEST: ====================================
*
* You might notice measureWrong_1 does not depend on $size, measureWrong_2 has troubles with
* linearity, and otherwise much faster than both measureRight_*. You can also see measureRight_2
* is marginally faster than measureRight_1.
*
* You can run this test:
*
* a) Via the command line:
* $ mvn clean install
* $ java -jar target/benchmarks.jar JMHSample_34
*
* b) Via the Java API:
* (see the JMH homepage for possible caveats when running from IDE:
* http://openjdk.java.net/projects/code-tools/jmh/)
*/
public static void main(String[] args) throws RunnerException {
Options opt = new OptionsBuilder()
.include(JMHSample_34_SafeLooping.class.getSimpleName())
.forks(3)
.build();
new Runner(opt).run();
}
}
| 7,541 | 35.970588 | 104 | java |
jmh | jmh-master/jmh-samples/src/main/java/org/openjdk/jmh/samples/JMHSample_35_Profilers.java | /*
* Copyright (c) 2014, Oracle America, Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* * Neither the name of Oracle nor the names of its contributors may be used
* to endorse or promote products derived from this software without
* specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
* THE POSSIBILITY OF SUCH DAMAGE.
*/
package org.openjdk.jmh.samples;
import org.openjdk.jmh.annotations.*;
import org.openjdk.jmh.infra.Blackhole;
import org.openjdk.jmh.profile.ClassloaderProfiler;
import org.openjdk.jmh.profile.DTraceAsmProfiler;
import org.openjdk.jmh.profile.LinuxPerfProfiler;
import org.openjdk.jmh.profile.StackProfiler;
import org.openjdk.jmh.runner.Runner;
import org.openjdk.jmh.runner.RunnerException;
import org.openjdk.jmh.runner.options.Options;
import org.openjdk.jmh.runner.options.OptionsBuilder;
import java.net.URL;
import java.net.URLClassLoader;
import java.util.HashMap;
import java.util.Map;
import java.util.TreeMap;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicLong;
public class JMHSample_35_Profilers {
/*
* This sample serves as the profiler overview.
*
* JMH has a few very handy profilers that help to understand your benchmarks. While
* these profilers are not the substitute for full-fledged external profilers, in many
* cases, these are handy to quickly dig into the benchmark behavior. When you are
* doing many cycles of tuning up the benchmark code itself, it is important to have
* a quick turnaround for the results.
*
* Use -lprof to list the profilers. There are quite a few profilers, and this sample
* would expand on a handful of most useful ones. Many profilers have their own options,
* usually accessible via -prof <profiler-name>:help.
*
* Since profilers are reporting on different things, it is hard to construct a single
* benchmark sample that will show all profilers in action. Therefore, we have a couple
* of benchmarks in this sample.
*/
/*
* ================================ MAPS BENCHMARK ================================
*/
@State(Scope.Thread)
@Warmup(iterations = 5, time = 1, timeUnit = TimeUnit.SECONDS)
@Measurement(iterations = 5, time = 1, timeUnit = TimeUnit.SECONDS)
@Fork(3)
@BenchmarkMode(Mode.AverageTime)
@OutputTimeUnit(TimeUnit.NANOSECONDS)
public static class Maps {
private Map<Integer, Integer> map;
@Param({"hashmap", "treemap"})
private String type;
private int begin;
private int end;
@Setup
public void setup() {
switch (type) {
case "hashmap":
map = new HashMap<>();
break;
case "treemap":
map = new TreeMap<>();
break;
default:
throw new IllegalStateException("Unknown type: " + type);
}
begin = 1;
end = 256;
for (int i = begin; i < end; i++) {
map.put(i, i);
}
}
@Benchmark
public void test(Blackhole bh) {
for (int i = begin; i < end; i++) {
bh.consume(map.get(i));
}
}
/*
* ============================== HOW TO RUN THIS TEST: ====================================
*
* You can run this test:
*
* a) Via the command line:
* $ mvn clean install
* $ java -jar target/benchmarks.jar JMHSample_35.*Maps -prof stack
* $ java -jar target/benchmarks.jar JMHSample_35.*Maps -prof gc
*
* b) Via the Java API:
* (see the JMH homepage for possible caveats when running from IDE:
* http://openjdk.java.net/projects/code-tools/jmh/)
*/
public static void main(String[] args) throws RunnerException {
Options opt = new OptionsBuilder()
.include(JMHSample_35_Profilers.Maps.class.getSimpleName())
.addProfiler(StackProfiler.class)
// .addProfiler(GCProfiler.class)
.build();
new Runner(opt).run();
}
/*
Running this benchmark will yield something like:
Benchmark (type) Mode Cnt Score Error Units
JMHSample_35_Profilers.Maps.test hashmap avgt 5 1553.201 ± 6.199 ns/op
JMHSample_35_Profilers.Maps.test treemap avgt 5 5177.065 ± 361.278 ns/op
Running with -prof stack will yield:
....[Thread state: RUNNABLE]........................................................................
99.0% 99.0% org.openjdk.jmh.samples.JMHSample_35_Profilers$Maps.test
0.4% 0.4% org.openjdk.jmh.samples.generated.JMHSample_35_Profilers_Maps_test.test_avgt_jmhStub
0.2% 0.2% sun.reflect.NativeMethodAccessorImpl.invoke0
0.2% 0.2% java.lang.Integer.valueOf
0.2% 0.2% sun.misc.Unsafe.compareAndSwapInt
....[Thread state: RUNNABLE]........................................................................
78.0% 78.0% java.util.TreeMap.getEntry
21.2% 21.2% org.openjdk.jmh.samples.JMHSample_35_Profilers$Maps.test
0.4% 0.4% java.lang.Integer.valueOf
0.2% 0.2% sun.reflect.NativeMethodAccessorImpl.invoke0
0.2% 0.2% org.openjdk.jmh.samples.generated.JMHSample_35_Profilers_Maps_test.test_avgt_jmhStub
Stack profiler is useful to quickly see if the code we are stressing actually executes. As many other
sampling profilers, it is susceptible for sampling bias: it can fail to notice quickly executing methods,
for example. In the benchmark above, it does not notice HashMap.get.
Next up, GC profiler. Running with -prof gc will yield:
Benchmark (type) Mode Cnt Score Error Units
JMHSample_35_Profilers.Maps.test hashmap avgt 5 1553.201 ± 6.199 ns/op
JMHSample_35_Profilers.Maps.test:·gc.alloc.rate hashmap avgt 5 1257.046 ± 5.675 MB/sec
JMHSample_35_Profilers.Maps.test:·gc.alloc.rate.norm hashmap avgt 5 2048.001 ± 0.001 B/op
JMHSample_35_Profilers.Maps.test:·gc.churn.PS_Eden_Space hashmap avgt 5 1259.148 ± 315.277 MB/sec
JMHSample_35_Profilers.Maps.test:·gc.churn.PS_Eden_Space.norm hashmap avgt 5 2051.519 ± 520.324 B/op
JMHSample_35_Profilers.Maps.test:·gc.churn.PS_Survivor_Space hashmap avgt 5 0.175 ± 0.386 MB/sec
JMHSample_35_Profilers.Maps.test:·gc.churn.PS_Survivor_Space.norm hashmap avgt 5 0.285 ± 0.629 B/op
JMHSample_35_Profilers.Maps.test:·gc.count hashmap avgt 5 29.000 counts
JMHSample_35_Profilers.Maps.test:·gc.time hashmap avgt 5 16.000 ms
JMHSample_35_Profilers.Maps.test treemap avgt 5 5177.065 ± 361.278 ns/op
JMHSample_35_Profilers.Maps.test:·gc.alloc.rate treemap avgt 5 377.251 ± 26.188 MB/sec
JMHSample_35_Profilers.Maps.test:·gc.alloc.rate.norm treemap avgt 5 2048.003 ± 0.001 B/op
JMHSample_35_Profilers.Maps.test:·gc.churn.PS_Eden_Space treemap avgt 5 392.743 ± 174.156 MB/sec
JMHSample_35_Profilers.Maps.test:·gc.churn.PS_Eden_Space.norm treemap avgt 5 2131.767 ± 913.941 B/op
JMHSample_35_Profilers.Maps.test:·gc.churn.PS_Survivor_Space treemap avgt 5 0.131 ± 0.215 MB/sec
JMHSample_35_Profilers.Maps.test:·gc.churn.PS_Survivor_Space.norm treemap avgt 5 0.709 ± 1.125 B/op
JMHSample_35_Profilers.Maps.test:·gc.count treemap avgt 5 25.000 counts
JMHSample_35_Profilers.Maps.test:·gc.time treemap avgt 5 26.000 ms
There, we can see that the tests are producing quite some garbage. "gc.alloc" would say we are allocating 1257
and 377 MB of objects per second, or 2048 bytes per benchmark operation. "gc.churn" would say that GC removes
the same amount of garbage from Eden space every second. In other words, we are producing 2048 bytes of garbage per
benchmark operation.
If you look closely at the test, you can get a (correct) hypothesis this is due to Integer autoboxing.
Note that "gc.alloc" counters generally produce more accurate data, but they can also fail when threads come and
go over the course of the benchmark. "gc.churn" values are updated on each GC event, and so if you want a more accurate
data, running longer and/or with small heap would help. But anyhow, always cross-reference "gc.alloc" and "gc.churn"
values with each other to get a complete picture.
It is also worth noticing that non-normalized counters are dependent on benchmark performance! Here, "treemap"
tests are 3x slower, and thus both allocation and churn rates are also comparably lower. It is often useful to look
into non-normalized counters to see if the test is allocation/GC-bound (figure the allocation pressure "ceiling"
for your configuration!), and normalized counters to see the more precise benchmark behavior.
As most profilers, both "stack" and "gc" profile are able to aggregate samples from multiple forks. It is a good
idea to run multiple forks with the profilers enabled, as it improves results error estimates.
*/
}
/*
* ================================ CLASSLOADER BENCHMARK ================================
*/
@State(Scope.Thread)
@Warmup(iterations = 5, time = 1, timeUnit = TimeUnit.SECONDS)
@Measurement(iterations = 5, time = 1, timeUnit = TimeUnit.SECONDS)
@Fork(3)
@BenchmarkMode(Mode.AverageTime)
@OutputTimeUnit(TimeUnit.NANOSECONDS)
public static class Classy {
/**
* Our own crippled classloader, that can only load a simple class over and over again.
*/
public static class XLoader extends URLClassLoader {
private static final byte[] X_BYTECODE = new byte[]{
(byte) 0xCA, (byte) 0xFE, (byte) 0xBA, (byte) 0xBE, 0x00, 0x00, 0x00, 0x34, 0x00, 0x0D, 0x0A, 0x00, 0x03, 0x00,
0x0A, 0x07, 0x00, 0x0B, 0x07, 0x00, 0x0C, 0x01, 0x00, 0x06, 0x3C, 0x69, 0x6E, 0x69, 0x74, 0x3E, 0x01, 0x00, 0x03,
0x28, 0x29, 0x56, 0x01, 0x00, 0x04, 0x43, 0x6F, 0x64, 0x65, 0x01, 0x00, 0x0F, 0x4C, 0x69, 0x6E, 0x65, 0x4E, 0x75,
0x6D, 0x62, 0x65, 0x72, 0x54, 0x61, 0x62, 0x6C, 0x65, 0x01, 0x00, 0x0A, 0x53, 0x6F, 0x75, 0x72, 0x63, 0x65, 0x46,
0x69, 0x6C, 0x65, 0x01, 0x00, 0x06, 0x58, 0x2E, 0x6A, 0x61, 0x76, 0x61, 0x0C, 0x00, 0x04, 0x00, 0x05, 0x01, 0x00,
0x01, 0x58, 0x01, 0x00, 0x10, 0x6A, 0x61, 0x76, 0x61, 0x2F, 0x6C, 0x61, 0x6E, 0x67, 0x2F, 0x4F, 0x62, 0x6A, 0x65,
0x63, 0x74, 0x00, 0x20, 0x00, 0x02, 0x00, 0x03, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x04, 0x00,
0x05, 0x00, 0x01, 0x00, 0x06, 0x00, 0x00, 0x00, 0x1D, 0x00, 0x01, 0x00, 0x01, 0x00, 0x00, 0x00, 0x05, 0x2A,
(byte) 0xB7, 0x00, 0x01, (byte) 0xB1, 0x00, 0x00, 0x00, 0x01, 0x00, 0x07, 0x00, 0x00, 0x00, 0x06, 0x00, 0x01, 0x00,
0x00, 0x00, 0x01, 0x00, 0x01, 0x00, 0x08, 0x00, 0x00, 0x00, 0x02, 0x00, 0x09,
};
public XLoader() {
super(new URL[0], ClassLoader.getSystemClassLoader());
}
@Override
protected Class<?> findClass(final String name) throws ClassNotFoundException {
return defineClass(name, X_BYTECODE, 0, X_BYTECODE.length);
}
}
@Benchmark
public Class<?> load() throws ClassNotFoundException {
return Class.forName("X", true, new XLoader());
}
/*
* ============================== HOW TO RUN THIS TEST: ====================================
*
* You can run this test:
*
* a) Via the command line:
* $ mvn clean install
* $ java -jar target/benchmarks.jar JMHSample_35.*Classy -prof cl
* $ java -jar target/benchmarks.jar JMHSample_35.*Classy -prof comp
*
* b) Via the Java API:
* (see the JMH homepage for possible caveats when running from IDE:
* http://openjdk.java.net/projects/code-tools/jmh/)
*/
public static void main(String[] args) throws RunnerException {
Options opt = new OptionsBuilder()
.include(JMHSample_35_Profilers.Classy.class.getSimpleName())
.addProfiler(ClassloaderProfiler.class)
// .addProfiler(CompilerProfiler.class)
.build();
new Runner(opt).run();
}
/*
Running with -prof cl will yield:
Benchmark Mode Cnt Score Error Units
JMHSample_35_Profilers.Classy.load avgt 15 34215.363 ± 545.892 ns/op
JMHSample_35_Profilers.Classy.load:·class.load avgt 15 29374.097 ± 716.743 classes/sec
JMHSample_35_Profilers.Classy.load:·class.load.norm avgt 15 1.000 ± 0.001 classes/op
JMHSample_35_Profilers.Classy.load:·class.unload avgt 15 29598.233 ± 3420.181 classes/sec
JMHSample_35_Profilers.Classy.load:·class.unload.norm avgt 15 1.008 ± 0.119 classes/op
Here, we can see the benchmark indeed load class per benchmark op, and this adds up to more than 29K classloads
per second. We can also see the runtime is able to successfully keep the number of loaded classes at bay,
since the class unloading happens at the same rate.
This profiler is handy when doing the classloading performance work, because it says if the classes
were actually loaded, and not reused across the Class.forName calls. It also helps to see if the benchmark
performs any classloading in the measurement phase. For example, if you have non-classloading benchmark,
you would expect these metrics be zero.
Another useful profiler that could tell if compiler is doing a heavy work in background, and thus interfering
with measurement, -prof comp:
Benchmark Mode Cnt Score Error Units
JMHSample_35_Profilers.Classy.load avgt 5 33523.875 ± 3026.025 ns/op
JMHSample_35_Profilers.Classy.load:·compiler.time.profiled avgt 5 5.000 ms
JMHSample_35_Profilers.Classy.load:·compiler.time.total avgt 5 479.000 ms
We seem to be at proper steady state: out of 479 ms of total compiler work, only 5 ms happen during the
measurement window. It is expected to have some level of background compilation even at steady state.
As most profilers, both "cl" and "comp" are able to aggregate samples from multiple forks. It is a good
idea to run multiple forks with the profilers enabled, as it improves results error estimates.
*/
}
/*
* ================================ ATOMIC LONG BENCHMARK ================================
*/
@State(Scope.Benchmark)
@Warmup(iterations = 5, time = 1, timeUnit = TimeUnit.SECONDS)
@Measurement(iterations = 5, time = 1, timeUnit = TimeUnit.SECONDS)
@Fork(1)
@BenchmarkMode(Mode.AverageTime)
@OutputTimeUnit(TimeUnit.NANOSECONDS)
public static class Atomic {
private AtomicLong n;
@Setup
public void setup() {
n = new AtomicLong();
}
@Benchmark
public long test() {
return n.incrementAndGet();
}
/*
* ============================== HOW TO RUN THIS TEST: ====================================
*
* You can run this test:
*
* a) Via the command line:
* $ mvn clean install
* $ java -jar target/benchmarks.jar JMHSample_35.*Atomic -prof perf -f 1 (Linux)
* $ java -jar target/benchmarks.jar JMHSample_35.*Atomic -prof perfnorm -f 3 (Linux)
* $ java -jar target/benchmarks.jar JMHSample_35.*Atomic -prof perfasm -f 1 (Linux)
* $ java -jar target/benchmarks.jar JMHSample_35.*Atomic -prof xperfasm -f 1 (Windows)
* $ java -jar target/benchmarks.jar JMHSample_35.*Atomic -prof dtraceasm -f 1 (Mac OS X)
* b) Via the Java API:
* (see the JMH homepage for possible caveats when running from IDE:
* http://openjdk.java.net/projects/code-tools/jmh/)
*/
public static void main(String[] args) throws RunnerException {
Options opt = new OptionsBuilder()
.include(JMHSample_35_Profilers.Atomic.class.getSimpleName())
.addProfiler(LinuxPerfProfiler.class)
// .addProfiler(LinuxPerfNormProfiler.class)
// .addProfiler(LinuxPerfAsmProfiler.class)
// .addProfiler(WinPerfAsmProfiler.class)
// .addProfiler(DTraceAsmProfiler.class)
.build();
new Runner(opt).run();
}
/*
Dealing with nanobenchmarks like these requires looking into the abyss of runtime, hardware, and
generated code. Luckily, JMH has a few handy tools that ease the pain. If you are running Linux,
then perf_events are probably available as standard package. This kernel facility taps into
hardware counters, and provides the data for user space programs like JMH. Windows has less
sophisticated facilities, but also usable, see below.
One can simply run "perf stat java -jar ..." to get the first idea how the workload behaves. In
JMH case, however, this will cause perf to profile both host and forked JVMs.
-prof perf avoids that: JMH invokes perf for the forked VM alone. For the benchmark above, it
would print something like:
Perf stats:
--------------------------------------------------
4172.776137 task-clock (msec) # 0.411 CPUs utilized
612 context-switches # 0.147 K/sec
31 cpu-migrations # 0.007 K/sec
195 page-faults # 0.047 K/sec
16,599,643,026 cycles # 3.978 GHz [30.80%]
<not supported> stalled-cycles-frontend
<not supported> stalled-cycles-backend
17,815,084,879 instructions # 1.07 insns per cycle [38.49%]
3,813,373,583 branches # 913.870 M/sec [38.56%]
1,212,788 branch-misses # 0.03% of all branches [38.91%]
7,582,256,427 L1-dcache-loads # 1817.077 M/sec [39.07%]
312,913 L1-dcache-load-misses # 0.00% of all L1-dcache hits [38.66%]
35,688 LLC-loads # 0.009 M/sec [32.58%]
<not supported> LLC-load-misses:HG
<not supported> L1-icache-loads:HG
161,436 L1-icache-load-misses:HG # 0.00% of all L1-icache hits [32.81%]
7,200,981,198 dTLB-loads:HG # 1725.705 M/sec [32.68%]
3,360 dTLB-load-misses:HG # 0.00% of all dTLB cache hits [32.65%]
193,874 iTLB-loads:HG # 0.046 M/sec [32.56%]
4,193 iTLB-load-misses:HG # 2.16% of all iTLB cache hits [32.44%]
<not supported> L1-dcache-prefetches:HG
0 L1-dcache-prefetch-misses:HG # 0.000 K/sec [32.33%]
10.159432892 seconds time elapsed
We can already see this benchmark goes with good IPC, does lots of loads and lots of stores,
all of them are more or less fulfilled without misses. The data like this is not handy though:
you would like to normalize the counters per benchmark op.
This is exactly what -prof perfnorm does:
Benchmark Mode Cnt Score Error Units
JMHSample_35_Profilers.Atomic.test avgt 15 6.551 ± 0.023 ns/op
JMHSample_35_Profilers.Atomic.test:·CPI avgt 3 0.933 ± 0.026 #/op
JMHSample_35_Profilers.Atomic.test:·L1-dcache-load-misses avgt 3 0.001 ± 0.022 #/op
JMHSample_35_Profilers.Atomic.test:·L1-dcache-loads avgt 3 12.267 ± 1.324 #/op
JMHSample_35_Profilers.Atomic.test:·L1-dcache-store-misses avgt 3 0.001 ± 0.006 #/op
JMHSample_35_Profilers.Atomic.test:·L1-dcache-stores avgt 3 4.090 ± 0.402 #/op
JMHSample_35_Profilers.Atomic.test:·L1-icache-load-misses avgt 3 0.001 ± 0.011 #/op
JMHSample_35_Profilers.Atomic.test:·LLC-loads avgt 3 0.001 ± 0.004 #/op
JMHSample_35_Profilers.Atomic.test:·LLC-stores avgt 3 ≈ 10⁻⁴ #/op
JMHSample_35_Profilers.Atomic.test:·branch-misses avgt 3 ≈ 10⁻⁴ #/op
JMHSample_35_Profilers.Atomic.test:·branches avgt 3 6.152 ± 0.385 #/op
JMHSample_35_Profilers.Atomic.test:·bus-cycles avgt 3 0.670 ± 0.048 #/op
JMHSample_35_Profilers.Atomic.test:·context-switches avgt 3 ≈ 10⁻⁶ #/op
JMHSample_35_Profilers.Atomic.test:·cpu-migrations avgt 3 ≈ 10⁻⁷ #/op
JMHSample_35_Profilers.Atomic.test:·cycles avgt 3 26.790 ± 1.393 #/op
JMHSample_35_Profilers.Atomic.test:·dTLB-load-misses avgt 3 ≈ 10⁻⁴ #/op
JMHSample_35_Profilers.Atomic.test:·dTLB-loads avgt 3 12.278 ± 0.277 #/op
JMHSample_35_Profilers.Atomic.test:·dTLB-store-misses avgt 3 ≈ 10⁻⁵ #/op
JMHSample_35_Profilers.Atomic.test:·dTLB-stores avgt 3 4.113 ± 0.437 #/op
JMHSample_35_Profilers.Atomic.test:·iTLB-load-misses avgt 3 ≈ 10⁻⁵ #/op
JMHSample_35_Profilers.Atomic.test:·iTLB-loads avgt 3 0.001 ± 0.034 #/op
JMHSample_35_Profilers.Atomic.test:·instructions avgt 3 28.729 ± 1.297 #/op
JMHSample_35_Profilers.Atomic.test:·minor-faults avgt 3 ≈ 10⁻⁷ #/op
JMHSample_35_Profilers.Atomic.test:·page-faults avgt 3 ≈ 10⁻⁷ #/op
JMHSample_35_Profilers.Atomic.test:·ref-cycles avgt 3 26.734 ± 2.081 #/op
It is customary to trim the lines irrelevant to the particular benchmark. We show all of them here for
completeness.
We can see that the benchmark does ~12 loads per benchmark op, and about ~4 stores per op, most of
them fitting in the cache. There are also ~6 branches per benchmark op, all are predicted as well.
It is also easy to see the benchmark op takes ~28 instructions executed in ~27 cycles.
The output would get more interesting when we run with more threads, say, -t 8:
Benchmark Mode Cnt Score Error Units
JMHSample_35_Profilers.Atomic.test avgt 15 143.595 ± 1.968 ns/op
JMHSample_35_Profilers.Atomic.test:·CPI avgt 3 17.741 ± 28.761 #/op
JMHSample_35_Profilers.Atomic.test:·L1-dcache-load-misses avgt 3 0.175 ± 0.406 #/op
JMHSample_35_Profilers.Atomic.test:·L1-dcache-loads avgt 3 11.872 ± 0.786 #/op
JMHSample_35_Profilers.Atomic.test:·L1-dcache-store-misses avgt 3 0.184 ± 0.505 #/op
JMHSample_35_Profilers.Atomic.test:·L1-dcache-stores avgt 3 4.422 ± 0.561 #/op
JMHSample_35_Profilers.Atomic.test:·L1-icache-load-misses avgt 3 0.015 ± 0.083 #/op
JMHSample_35_Profilers.Atomic.test:·LLC-loads avgt 3 0.015 ± 0.128 #/op
JMHSample_35_Profilers.Atomic.test:·LLC-stores avgt 3 1.036 ± 0.045 #/op
JMHSample_35_Profilers.Atomic.test:·branch-misses avgt 3 0.224 ± 0.492 #/op
JMHSample_35_Profilers.Atomic.test:·branches avgt 3 6.524 ± 2.873 #/op
JMHSample_35_Profilers.Atomic.test:·bus-cycles avgt 3 13.475 ± 14.502 #/op
JMHSample_35_Profilers.Atomic.test:·context-switches avgt 3 ≈ 10⁻⁴ #/op
JMHSample_35_Profilers.Atomic.test:·cpu-migrations avgt 3 ≈ 10⁻⁶ #/op
JMHSample_35_Profilers.Atomic.test:·cycles avgt 3 537.874 ± 595.723 #/op
JMHSample_35_Profilers.Atomic.test:·dTLB-load-misses avgt 3 0.001 ± 0.006 #/op
JMHSample_35_Profilers.Atomic.test:·dTLB-loads avgt 3 12.032 ± 2.430 #/op
JMHSample_35_Profilers.Atomic.test:·dTLB-store-misses avgt 3 ≈ 10⁻⁴ #/op
JMHSample_35_Profilers.Atomic.test:·dTLB-stores avgt 3 4.557 ± 0.948 #/op
JMHSample_35_Profilers.Atomic.test:·iTLB-load-misses avgt 3 ≈ 10⁻³ #/op
JMHSample_35_Profilers.Atomic.test:·iTLB-loads avgt 3 0.016 ± 0.052 #/op
JMHSample_35_Profilers.Atomic.test:·instructions avgt 3 30.367 ± 15.052 #/op
JMHSample_35_Profilers.Atomic.test:·minor-faults avgt 3 ≈ 10⁻⁵ #/op
JMHSample_35_Profilers.Atomic.test:·page-faults avgt 3 ≈ 10⁻⁵ #/op
JMHSample_35_Profilers.Atomic.test:·ref-cycles avgt 3 538.697 ± 590.183 #/op
Note how this time the CPI is awfully high: 17 cycles per instruction! Indeed, we are making almost the
same ~30 instructions, but now they take >530 cycles. Other counters highlight why: we now have cache
misses on both loads and stores, on all levels of cache hierarchy. With a simple constant-footprint
like ours, that's an indication of sharing problems. Indeed, our AtomicLong is heavily-contended
with 8 threads.
"perfnorm", again, can (and should!) be used with multiple forks, to properly estimate the metrics.
The last, but not the least player on our field is -prof perfasm. It is important to follow up on
generated code when dealing with fine-grained benchmarks. We could employ PrintAssembly to dump the
generated code, but it will dump *all* the generated code, and figuring out what is related to our
benchmark is a daunting task. But we have "perf" that can tell what program addresses are really hot!
This enables us to contrast the assembly output.
-prof perfasm would indeed contrast out the hottest loop in the generated code! It will also point
fingers at "lock xadd" as the hottest instruction in our code. Hardware counters are not very precise
about the instruction addresses, so sometimes they attribute the events to the adjacent code lines.
Hottest code regions (>10.00% "cycles" events):
....[Hottest Region 1]..............................................................................
[0x7f1824f87c45:0x7f1824f87c79] in org.openjdk.jmh.samples.generated.JMHSample_35_Profilers_Atomic_test::test_avgt_jmhStub
; - org.openjdk.jmh.samples.generated.JMHSample_35_Profilers_Atomic_test::test_avgt_jmhStub@29 (line 201)
; implicit exception: dispatches to 0x00007f1824f87d21
0x00007f1824f87c25: test %r11d,%r11d
0x00007f1824f87c28: jne 0x00007f1824f87cbd ;*ifeq
; - org.openjdk.jmh.samples.generated.JMHSample_35_Profilers_Atomic_test::test_avgt_jmhStub@32 (line 201)
0x00007f1824f87c2e: mov $0x1,%ebp
0x00007f1824f87c33: nopw 0x0(%rax,%rax,1)
0x00007f1824f87c3c: xchg %ax,%ax ;*aload
; - org.openjdk.jmh.samples.generated.JMHSample_35_Profilers_Atomic_test::test_avgt_jmhStub@13 (line 199)
0x00007f1824f87c40: mov 0x8(%rsp),%r10
0.00% 0x00007f1824f87c45: mov 0xc(%r10),%r11d ;*getfield n
; - org.openjdk.jmh.samples.JMHSample_35_Profilers$Atomic::test@1 (line 280)
; - org.openjdk.jmh.samples.generated.JMHSample_35_Profilers_Atomic_test::test_avgt_jmhStub@16 (line 199)
0.19% 0.02% 0x00007f1824f87c49: test %r11d,%r11d
0x00007f1824f87c4c: je 0x00007f1824f87cad
0x00007f1824f87c4e: mov $0x1,%edx
0x00007f1824f87c53: lock xadd %rdx,0x10(%r12,%r11,8)
;*invokevirtual getAndAddLong
; - java.util.concurrent.atomic.AtomicLong::incrementAndGet@8 (line 200)
; - org.openjdk.jmh.samples.JMHSample_35_Profilers$Atomic::test@4 (line 280)
; - org.openjdk.jmh.samples.generated.JMHSample_35_Profilers_Atomic_test::test_avgt_jmhStub@16 (line 199)
95.20% 95.06% 0x00007f1824f87c5a: add $0x1,%rdx ;*ladd
; - java.util.concurrent.atomic.AtomicLong::incrementAndGet@12 (line 200)
; - org.openjdk.jmh.samples.JMHSample_35_Profilers$Atomic::test@4 (line 280)
; - org.openjdk.jmh.samples.generated.JMHSample_35_Profilers_Atomic_test::test_avgt_jmhStub@16 (line 199)
0.24% 0.00% 0x00007f1824f87c5e: mov 0x10(%rsp),%rsi
0x00007f1824f87c63: callq 0x00007f1824e2b020 ; OopMap{[0]=Oop [8]=Oop [16]=Oop [24]=Oop off=232}
;*invokevirtual consume
; - org.openjdk.jmh.samples.generated.JMHSample_35_Profilers_Atomic_test::test_avgt_jmhStub@19 (line 199)
; {optimized virtual_call}
0.20% 0.01% 0x00007f1824f87c68: mov 0x18(%rsp),%r10
0x00007f1824f87c6d: movzbl 0x94(%r10),%r11d ;*getfield isDone
; - org.openjdk.jmh.samples.generated.JMHSample_35_Profilers_Atomic_test::test_avgt_jmhStub@29 (line 201)
0.00% 0x00007f1824f87c75: add $0x1,%rbp ; OopMap{r10=Oop [0]=Oop [8]=Oop [16]=Oop [24]=Oop off=249}
;*ifeq
; - org.openjdk.jmh.samples.generated.JMHSample_35_Profilers_Atomic_test::test_avgt_jmhStub@32 (line 201)
0.20% 0.01% 0x00007f1824f87c79: test %eax,0x15f36381(%rip) # 0x00007f183aebe000
; {poll}
0x00007f1824f87c7f: test %r11d,%r11d
0x00007f1824f87c82: je 0x00007f1824f87c40 ;*aload_2
; - org.openjdk.jmh.samples.generated.JMHSample_35_Profilers_Atomic_test::test_avgt_jmhStub@35 (line 202)
0x00007f1824f87c84: mov $0x7f1839be4220,%r10
0x00007f1824f87c8e: callq *%r10 ;*invokestatic nanoTime
; - org.openjdk.jmh.samples.generated.JMHSample_35_Profilers_Atomic_test::test_avgt_jmhStub@36 (line 202)
0x00007f1824f87c91: mov (%rsp),%r10
....................................................................................................
96.03% 95.10% <total for region 1>
perfasm would also print the hottest methods to show if we indeed spending time in our benchmark. Most of the time,
it can demangle VM and kernel symbols as well:
....[Hottest Methods (after inlining)]..............................................................
96.03% 95.10% org.openjdk.jmh.samples.generated.JMHSample_35_Profilers_Atomic_test::test_avgt_jmhStub
0.73% 0.78% org.openjdk.jmh.samples.generated.JMHSample_35_Profilers_Atomic_test::test_AverageTime
0.63% 0.00% org.openjdk.jmh.infra.Blackhole::consume
0.23% 0.25% native_write_msr_safe ([kernel.kallsyms])
0.09% 0.05% _raw_spin_unlock ([kernel.kallsyms])
0.09% 0.00% [unknown] (libpthread-2.19.so)
0.06% 0.07% _raw_spin_lock ([kernel.kallsyms])
0.06% 0.04% _raw_spin_unlock_irqrestore ([kernel.kallsyms])
0.06% 0.05% _IO_fwrite (libc-2.19.so)
0.05% 0.03% __srcu_read_lock; __srcu_read_unlock ([kernel.kallsyms])
0.04% 0.05% _raw_spin_lock_irqsave ([kernel.kallsyms])
0.04% 0.06% vfprintf (libc-2.19.so)
0.04% 0.01% mutex_unlock ([kernel.kallsyms])
0.04% 0.01% _nv014306rm ([nvidia])
0.04% 0.04% rcu_eqs_enter_common.isra.47 ([kernel.kallsyms])
0.04% 0.02% mutex_lock ([kernel.kallsyms])
0.03% 0.07% __acct_update_integrals ([kernel.kallsyms])
0.03% 0.02% fget_light ([kernel.kallsyms])
0.03% 0.01% fput ([kernel.kallsyms])
0.03% 0.04% rcu_eqs_exit_common.isra.48 ([kernel.kallsyms])
1.63% 2.26% <...other 319 warm methods...>
....................................................................................................
100.00% 98.97% <totals>
....[Distribution by Area]..........................................................................
97.44% 95.99% <generated code>
1.60% 2.42% <native code in ([kernel.kallsyms])>
0.47% 0.78% <native code in (libjvm.so)>
0.22% 0.29% <native code in (libc-2.19.so)>
0.15% 0.07% <native code in (libpthread-2.19.so)>
0.07% 0.38% <native code in ([nvidia])>
0.05% 0.06% <native code in (libhsdis-amd64.so)>
0.00% 0.00% <native code in (nf_conntrack.ko)>
0.00% 0.00% <native code in (hid.ko)>
....................................................................................................
100.00% 100.00% <totals>
Since program addresses change from fork to fork, it does not make sense to run perfasm with more than
a single fork.
*/
}
}
| 39,852 | 65.311148 | 187 | java |
jmh | jmh-master/jmh-samples/src/main/java/org/openjdk/jmh/samples/JMHSample_36_BranchPrediction.java | /*
* Copyright (c) 2015, Oracle America, Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* * Neither the name of Oracle nor the names of its contributors may be used
* to endorse or promote products derived from this software without
* specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
* THE POSSIBILITY OF SUCH DAMAGE.
*/
package org.openjdk.jmh.samples;
import org.openjdk.jmh.annotations.*;
import org.openjdk.jmh.infra.Blackhole;
import org.openjdk.jmh.runner.Runner;
import org.openjdk.jmh.runner.RunnerException;
import org.openjdk.jmh.runner.options.Options;
import org.openjdk.jmh.runner.options.OptionsBuilder;
import java.util.Arrays;
import java.util.Random;
import java.util.concurrent.TimeUnit;
@BenchmarkMode(Mode.AverageTime)
@OutputTimeUnit(TimeUnit.NANOSECONDS)
@Warmup(iterations = 5, time = 1, timeUnit = TimeUnit.SECONDS)
@Measurement(iterations = 5, time = 1, timeUnit = TimeUnit.SECONDS)
@Fork(5)
@State(Scope.Benchmark)
public class JMHSample_36_BranchPrediction {
/*
* This sample serves as a warning against regular data sets.
*
* It is very tempting to present a regular data set to benchmark, either due to
* naive generation strategy, or just from feeling better about regular data sets.
* Unfortunately, it frequently backfires: the regular datasets are known to be
* optimized well by software and hardware. This example exploits one of these
* optimizations: branch prediction.
*
* Imagine our benchmark selects the branch based on the array contents, as
* we are streaming through it:
*/
private static final int COUNT = 1024 * 1024;
private byte[] sorted;
private byte[] unsorted;
@Setup
public void setup() {
sorted = new byte[COUNT];
unsorted = new byte[COUNT];
Random random = new Random(1234);
random.nextBytes(sorted);
random.nextBytes(unsorted);
Arrays.sort(sorted);
}
@Benchmark
@OperationsPerInvocation(COUNT)
public void sorted(Blackhole bh1, Blackhole bh2) {
for (byte v : sorted) {
if (v > 0) {
bh1.consume(v);
} else {
bh2.consume(v);
}
}
}
@Benchmark
@OperationsPerInvocation(COUNT)
public void unsorted(Blackhole bh1, Blackhole bh2) {
for (byte v : unsorted) {
if (v > 0) {
bh1.consume(v);
} else {
bh2.consume(v);
}
}
}
/*
There is a substantial difference in performance for these benchmarks!
It is explained by good branch prediction in "sorted" case, and branch mispredicts in "unsorted"
case. -prof perfnorm conveniently highlights that, with larger "branch-misses", and larger "CPI"
for "unsorted" case:
Benchmark Mode Cnt Score Error Units
JMHSample_36_BranchPrediction.sorted avgt 25 2.160 ± 0.049 ns/op
JMHSample_36_BranchPrediction.sorted:·CPI avgt 5 0.286 ± 0.025 #/op
JMHSample_36_BranchPrediction.sorted:·branch-misses avgt 5 ≈ 10⁻⁴ #/op
JMHSample_36_BranchPrediction.sorted:·branches avgt 5 7.606 ± 1.742 #/op
JMHSample_36_BranchPrediction.sorted:·cycles avgt 5 8.998 ± 1.081 #/op
JMHSample_36_BranchPrediction.sorted:·instructions avgt 5 31.442 ± 4.899 #/op
JMHSample_36_BranchPrediction.unsorted avgt 25 5.943 ± 0.018 ns/op
JMHSample_36_BranchPrediction.unsorted:·CPI avgt 5 0.775 ± 0.052 #/op
JMHSample_36_BranchPrediction.unsorted:·branch-misses avgt 5 0.529 ± 0.026 #/op <--- OOPS
JMHSample_36_BranchPrediction.unsorted:·branches avgt 5 7.841 ± 0.046 #/op
JMHSample_36_BranchPrediction.unsorted:·cycles avgt 5 24.793 ± 0.434 #/op
JMHSample_36_BranchPrediction.unsorted:·instructions avgt 5 31.994 ± 2.342 #/op
It is an open question if you want to measure only one of these tests. In many cases, you have to measure
both to get the proper best-case and worst-case estimate!
*/
/*
* ============================== HOW TO RUN THIS TEST: ====================================
*
* You can run this test:
*
* a) Via the command line:
* $ mvn clean install
* $ java -jar target/benchmarks.jar JMHSample_36
*
* b) Via the Java API:
* (see the JMH homepage for possible caveats when running from IDE:
* http://openjdk.java.net/projects/code-tools/jmh/)
*/
public static void main(String[] args) throws RunnerException {
Options opt = new OptionsBuilder()
.include(".*" + JMHSample_36_BranchPrediction.class.getSimpleName() + ".*")
.build();
new Runner(opt).run();
}
}
| 6,390 | 40.771242 | 116 | java |
jmh | jmh-master/jmh-samples/src/main/java/org/openjdk/jmh/samples/JMHSample_37_CacheAccess.java | /*
* Copyright (c) 2015, Oracle America, Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* * Neither the name of Oracle nor the names of its contributors may be used
* to endorse or promote products derived from this software without
* specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
* THE POSSIBILITY OF SUCH DAMAGE.
*/
package org.openjdk.jmh.samples;
import org.openjdk.jmh.annotations.*;
import org.openjdk.jmh.infra.Blackhole;
import org.openjdk.jmh.runner.Runner;
import org.openjdk.jmh.runner.RunnerException;
import org.openjdk.jmh.runner.options.Options;
import org.openjdk.jmh.runner.options.OptionsBuilder;
import java.util.Random;
import java.util.concurrent.TimeUnit;
@BenchmarkMode(Mode.AverageTime)
@OutputTimeUnit(TimeUnit.NANOSECONDS)
@Warmup(iterations = 5, time = 1, timeUnit = TimeUnit.SECONDS)
@Measurement(iterations = 5, time = 1, timeUnit = TimeUnit.SECONDS)
@Fork(5)
@State(Scope.Benchmark)
public class JMHSample_37_CacheAccess {
/*
* This sample serves as a warning against subtle differences in cache access patterns.
*
* Many performance differences may be explained by the way tests are accessing memory.
* In the example below, we walk the matrix either row-first, or col-first:
*/
private final static int COUNT = 4096;
private final static int MATRIX_SIZE = COUNT * COUNT;
private int[][] matrix;
@Setup
public void setup() {
matrix = new int[COUNT][COUNT];
Random random = new Random(1234);
for (int i = 0; i < COUNT; i++) {
for (int j = 0; j < COUNT; j++) {
matrix[i][j] = random.nextInt();
}
}
}
@Benchmark
@OperationsPerInvocation(MATRIX_SIZE)
public void colFirst(Blackhole bh) {
for (int c = 0; c < COUNT; c++) {
for (int r = 0; r < COUNT; r++) {
bh.consume(matrix[r][c]);
}
}
}
@Benchmark
@OperationsPerInvocation(MATRIX_SIZE)
public void rowFirst(Blackhole bh) {
for (int r = 0; r < COUNT; r++) {
for (int c = 0; c < COUNT; c++) {
bh.consume(matrix[r][c]);
}
}
}
/*
Notably, colFirst accesses are much slower, and that's not a surprise: Java's multidimensional
arrays are actually rigged, being one-dimensional arrays of one-dimensional arrays. Therefore,
pulling n-th element from each of the inner array induces more cache misses, when matrix is large.
-prof perfnorm conveniently highlights that, with >2 cache misses per one benchmark op:
Benchmark Mode Cnt Score Error Units
JMHSample_37_MatrixCopy.colFirst avgt 25 5.306 ± 0.020 ns/op
JMHSample_37_MatrixCopy.colFirst:·CPI avgt 5 0.621 ± 0.011 #/op
JMHSample_37_MatrixCopy.colFirst:·L1-dcache-load-misses avgt 5 2.177 ± 0.044 #/op <-- OOPS
JMHSample_37_MatrixCopy.colFirst:·L1-dcache-loads avgt 5 14.804 ± 0.261 #/op
JMHSample_37_MatrixCopy.colFirst:·LLC-loads avgt 5 2.165 ± 0.091 #/op
JMHSample_37_MatrixCopy.colFirst:·cycles avgt 5 22.272 ± 0.372 #/op
JMHSample_37_MatrixCopy.colFirst:·instructions avgt 5 35.888 ± 1.215 #/op
JMHSample_37_MatrixCopy.rowFirst avgt 25 2.662 ± 0.003 ns/op
JMHSample_37_MatrixCopy.rowFirst:·CPI avgt 5 0.312 ± 0.003 #/op
JMHSample_37_MatrixCopy.rowFirst:·L1-dcache-load-misses avgt 5 0.066 ± 0.001 #/op
JMHSample_37_MatrixCopy.rowFirst:·L1-dcache-loads avgt 5 14.570 ± 0.400 #/op
JMHSample_37_MatrixCopy.rowFirst:·LLC-loads avgt 5 0.002 ± 0.001 #/op
JMHSample_37_MatrixCopy.rowFirst:·cycles avgt 5 11.046 ± 0.343 #/op
JMHSample_37_MatrixCopy.rowFirst:·instructions avgt 5 35.416 ± 1.248 #/op
So, when comparing two different benchmarks, you have to follow up if the difference is caused
by the memory locality issues.
*/
/*
* ============================== HOW TO RUN THIS TEST: ====================================
*
* You can run this test:
*
* a) Via the command line:
* $ mvn clean install
* $ java -jar target/benchmarks.jar JMHSample_37
*
* b) Via the Java API:
* (see the JMH homepage for possible caveats when running from IDE:
* http://openjdk.java.net/projects/code-tools/jmh/)
*/
public static void main(String[] args) throws RunnerException {
Options opt = new OptionsBuilder()
.include(".*" + JMHSample_37_CacheAccess.class.getSimpleName() + ".*")
.build();
new Runner(opt).run();
}
}
| 6,232 | 42.587413 | 108 | java |
jmh | jmh-master/jmh-samples/src/main/java/org/openjdk/jmh/samples/JMHSample_38_PerInvokeSetup.java | /*
* Copyright (c) 2015, Oracle America, Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* * Neither the name of Oracle nor the names of its contributors may be used
* to endorse or promote products derived from this software without
* specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
* THE POSSIBILITY OF SUCH DAMAGE.
*/
package org.openjdk.jmh.samples;
import org.openjdk.jmh.annotations.*;
import org.openjdk.jmh.runner.Runner;
import org.openjdk.jmh.runner.RunnerException;
import org.openjdk.jmh.runner.options.Options;
import org.openjdk.jmh.runner.options.OptionsBuilder;
import java.util.Arrays;
import java.util.Random;
import java.util.concurrent.TimeUnit;
@BenchmarkMode(Mode.AverageTime)
@OutputTimeUnit(TimeUnit.NANOSECONDS)
@Warmup(iterations = 5, time = 1, timeUnit = TimeUnit.SECONDS)
@Measurement(iterations = 5, time = 1, timeUnit = TimeUnit.SECONDS)
@Fork(5)
public class JMHSample_38_PerInvokeSetup {
/*
* This example highlights the usual mistake in non-steady-state benchmarks.
*
* Suppose we want to test how long it takes to bubble sort an array. Naively,
* we could make the test that populates an array with random (unsorted) values,
* and calls sort on it over and over again:
*/
private void bubbleSort(byte[] b) {
boolean changed = true;
while (changed) {
changed = false;
for (int c = 0; c < b.length - 1; c++) {
if (b[c] > b[c + 1]) {
byte t = b[c];
b[c] = b[c + 1];
b[c + 1] = t;
changed = true;
}
}
}
}
// Could be an implicit State instead, but we are going to use it
// as the dependency in one of the tests below
@State(Scope.Benchmark)
public static class Data {
@Param({"1", "16", "256"})
int count;
byte[] arr;
@Setup
public void setup() {
arr = new byte[count];
Random random = new Random(1234);
random.nextBytes(arr);
}
}
@Benchmark
public byte[] measureWrong(Data d) {
bubbleSort(d.arr);
return d.arr;
}
/*
* The method above is subtly wrong: it sorts the random array on the first invocation
* only. Every subsequent call will "sort" the already sorted array. With bubble sort,
* that operation would be significantly faster!
*
* This is how we might *try* to measure it right by making a copy in Level.Invocation
* setup. However, this is susceptible to the problems described in Level.Invocation
* Javadocs, READ AND UNDERSTAND THOSE DOCS BEFORE USING THIS APPROACH.
*/
@State(Scope.Thread)
public static class DataCopy {
byte[] copy;
@Setup(Level.Invocation)
public void setup2(Data d) {
copy = Arrays.copyOf(d.arr, d.arr.length);
}
}
@Benchmark
public byte[] measureNeutral(DataCopy d) {
bubbleSort(d.copy);
return d.copy;
}
/*
* In an overwhelming majority of cases, the only sensible thing to do is to suck up
* the per-invocation setup costs into a benchmark itself. This work well in practice,
* especially when the payload costs dominate the setup costs.
*/
@Benchmark
public byte[] measureRight(Data d) {
byte[] c = Arrays.copyOf(d.arr, d.arr.length);
bubbleSort(c);
return c;
}
/*
Benchmark (count) Mode Cnt Score Error Units
JMHSample_38_PerInvokeSetup.measureWrong 1 avgt 25 2.408 ± 0.011 ns/op
JMHSample_38_PerInvokeSetup.measureWrong 16 avgt 25 8.286 ± 0.023 ns/op
JMHSample_38_PerInvokeSetup.measureWrong 256 avgt 25 73.405 ± 0.018 ns/op
JMHSample_38_PerInvokeSetup.measureNeutral 1 avgt 25 15.835 ± 0.470 ns/op
JMHSample_38_PerInvokeSetup.measureNeutral 16 avgt 25 112.552 ± 0.787 ns/op
JMHSample_38_PerInvokeSetup.measureNeutral 256 avgt 25 58343.848 ± 991.202 ns/op
JMHSample_38_PerInvokeSetup.measureRight 1 avgt 25 6.075 ± 0.018 ns/op
JMHSample_38_PerInvokeSetup.measureRight 16 avgt 25 102.390 ± 0.676 ns/op
JMHSample_38_PerInvokeSetup.measureRight 256 avgt 25 58812.411 ± 997.951 ns/op
We can clearly see that "measureWrong" provides a very weird result: it "sorts" way too fast.
"measureNeutral" is neither good or bad: while it prepares the data for each invocation correctly,
the timing overheads are clearly visible. These overheads can be overwhelming, depending on
the thread count and/or OS flavor.
*/
/*
* ============================== HOW TO RUN THIS TEST: ====================================
*
* You can run this test:
*
* a) Via the command line:
* $ mvn clean install
* $ java -jar target/benchmarks.jar JMHSample_38
*
* b) Via the Java API:
* (see the JMH homepage for possible caveats when running from IDE:
* http://openjdk.java.net/projects/code-tools/jmh/)
*/
public static void main(String[] args) throws RunnerException {
Options opt = new OptionsBuilder()
.include(".*" + JMHSample_38_PerInvokeSetup.class.getSimpleName() + ".*")
.build();
new Runner(opt).run();
}
}
| 6,816 | 37.083799 | 106 | java |
jmh | jmh-master/jmh-samples/src/main/java/org/openjdk/jmh/samples/JMHSample_39_MemoryAccess.java | /*
* Copyright (c) 2015, Oracle America, Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* * Neither the name of Oracle nor the names of its contributors may be used
* to endorse or promote products derived from this software without
* specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
* THE POSSIBILITY OF SUCH DAMAGE.
*/
package org.openjdk.jmh.samples;
import org.openjdk.jmh.annotations.*;
import org.openjdk.jmh.runner.Runner;
import org.openjdk.jmh.runner.RunnerException;
import org.openjdk.jmh.runner.options.Options;
import org.openjdk.jmh.runner.options.OptionsBuilder;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Random;
import java.util.concurrent.TimeUnit;
@BenchmarkMode(Mode.AverageTime)
@OutputTimeUnit(TimeUnit.MILLISECONDS)
@Warmup(iterations = 5, time = 1, timeUnit = TimeUnit.SECONDS)
@Measurement(iterations = 5, time = 1, timeUnit = TimeUnit.SECONDS)
@Fork(5)
@State(Scope.Benchmark)
public class JMHSample_39_MemoryAccess {
public static final int N = 20_000_000;
/*
* This example highlights the pitfall of accidentally measuring memory access instead of processing time.
*
* An int array has got a different memory layout than an ArrayList of boxed ints.
* This can lead to useless results because the memory access is completely different.
* Arrays save all their ints in one block on the heap while ArrayLists don't.
* They save only references to the boxed ints in one block.
* All the references point to the boxed ints which are usually spread all over the heap.
* This leads to many cache misses with a big error:
*
* Benchmark Mode Cnt Score Error Units
* JMHSample_39_MemoryAccess.sumArray avgt 25 4.887 ± 0.008 ms/op
* JMHSample_39_MemoryAccess.sumArrayList avgt 25 35.765 ± 0.112 ms/op
* JMHSample_39_MemoryAccess.sumArrayListShuffled avgt 25 169.301 ± 1.064 ms/op
*
* The Java Object Layout (JOL) is a tool with which the different memory layouts of arrays and ArrayLists can be
* examined in more detail.
*/
private int[] intArray = new int[N];
private List<Integer> intList = new ArrayList<>(N);
private List<Integer> shuffledIntList = new ArrayList<>(N);
@Setup
public void setup() {
Random random = new Random(1234);
for (int i = 0; i < N; i++) {
intArray[i] = random.nextInt();
intList.add(intArray[i]);
shuffledIntList.add(intArray[i]);
}
Collections.shuffle(shuffledIntList);
}
@Benchmark
public long sumArray() {
long sum = 0;
for (int i = 0; i < N; i++) {
sum += intArray[i];
}
return sum;
}
@Benchmark
public long sumArrayList() {
long sum = 0;
for (int i = 0; i < N; i++) {
sum += intList.get(i);
}
return sum;
}
@Benchmark
public long sumArrayListShuffled() {
long sum = 0;
for (int i = 0; i < N; i++) {
sum += shuffledIntList.get(i);
}
return sum;
}
/*
* ============================== HOW TO RUN THIS TEST: ====================================
*
* You can run this test:
*
* a) Via the command line:
* $ mvn clean install
* $ java -jar target/benchmarks.jar JMHSample_39
*
* b) Via the Java API:
* (see the JMH homepage for possible caveats when running from IDE:
* http://openjdk.java.net/projects/code-tools/jmh/)
*/
public static void main(String[] args) throws RunnerException {
Options opt = new OptionsBuilder()
.include(".*" + JMHSample_39_MemoryAccess.class.getSimpleName() + ".*")
.build();
new Runner(opt).run();
}
}
| 5,167 | 37 | 117 | java |
wsdmcup17-data-server | wsdmcup17-data-server-master/src/main/java/org/wsdmcup17/dataserver/Configuration.java | package org.wsdmcup17.dataserver;
import java.io.File;
public class Configuration {
private static final String
ERROR_MSG_INCONSISTENT_CONFIGURATION =
"Inconsistent configuration for production: dataset name missing.";
private File revisionFile;
private File metadataFile;
private File outputPath;
private int port;
private File tiraPath;
private boolean isInProductionMode;
private String tiraDatasetName;
public Configuration(String revisionFileName, String metadataFileName,
String outputPath, int port, String tiraPath,
String tiraDatasetName) {
this.revisionFile = new File(revisionFileName);
this.metadataFile = new File(metadataFileName);
this.outputPath = new File(outputPath);
this.port = port;
this.tiraPath = tiraPath != null ? new File(tiraPath) : null;
this.tiraDatasetName = tiraDatasetName;
if (tiraPath != null) {
if (tiraDatasetName != null) {
this.isInProductionMode = true;
}
else {
throw new Error(ERROR_MSG_INCONSISTENT_CONFIGURATION);
}
}
}
public File getRevisionFile() {
return revisionFile;
}
public File getMetadataFile() {
return metadataFile;
}
public File getOutputPath() {
return outputPath;
}
public File getTiraPath() {
return tiraPath;
}
public int getPort() {
return port;
}
public String getTiraDatasetName() {
return tiraDatasetName;
}
public boolean isInProductionMode() {
return isInProductionMode;
}
}
| 1,449 | 20.641791 | 71 | java |
wsdmcup17-data-server | wsdmcup17-data-server-master/src/main/java/org/wsdmcup17/dataserver/Main.java | package org.wsdmcup17.dataserver;
import java.io.File;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.nio.charset.Charset;
import org.apache.commons.cli.CommandLine;
import org.apache.commons.cli.CommandLineParser;
import org.apache.commons.cli.DefaultParser;
import org.apache.commons.cli.HelpFormatter;
import org.apache.commons.cli.Option;
import org.apache.commons.cli.Options;
import org.apache.commons.cli.ParseException;
import org.slf4j.LoggerFactory;
import ch.qos.logback.classic.AsyncAppender;
import ch.qos.logback.classic.Logger;
import ch.qos.logback.classic.LoggerContext;
import ch.qos.logback.classic.encoder.PatternLayoutEncoder;
import ch.qos.logback.classic.sift.MDCBasedDiscriminator;
import ch.qos.logback.classic.sift.SiftingAppender;
import ch.qos.logback.classic.spi.ILoggingEvent;
import ch.qos.logback.core.Appender;
import ch.qos.logback.core.ConsoleAppender;
import ch.qos.logback.core.Context;
import ch.qos.logback.core.FileAppender;
import ch.qos.logback.core.encoder.Encoder;
import ch.qos.logback.core.joran.spi.JoranException;
import ch.qos.logback.core.sift.AppenderFactory;
import ch.qos.logback.core.util.Duration;
public class Main {
private static final String
WSDM_CUP_2017_DATA_SERVER = "WSDM Cup 2017 Data Server",
OPT_REVISION_FILE = "r",
OPT_REVISION_FILE_LONG = "revision",
OPT_REVISION_FILE_DESC = "Revision file",
OPT_METADATA_FILE = "m",
OPT_METADATA_FILE_LONG = "metadata",
OPT_METADATA_FILE_DESC = "Metadata file",
OPT_OUTPUT_PATH = "o",
OPT_OUTPUT_PATH_LONG = "outputpath",
OPT_OUTPUT_PATH_DESC = "Output path",
OPT_PORT = "p",
OPT_PORT_LONG = "port",
OPT_PORT_DESC = "Port",
OPT_TIRA_PATH = "t",
OPT_TIRA_PATH_LONG = "tirapath",
OPT_TIRA_PATH_DESC = "TIRA path",
OPT_TIRA_DATASET_NAME = "d",
OPT_TIRA_DATASET_NAME_LONG = "datasetname",
OPT_TIRA_DATASET_NAME_DESC = "TIRA dataset name",
LOG_PATTERN = "[%d{yyyy-MM-dd HH:mm:ss}] [%-5p] [%t] [%c{0}] %m%n",
UTF_8 = "UTF-8",
EXT_LOG = ".log";
private static final Duration STALE_APPENDER_TIMEOUT =
Duration.buildByDays(14);
private static LoggerContext logContext;
public static void main(String[] args) throws UnknownHostException {
CommandLine cmd = parseArgs(args);
Configuration config = new Configuration(
cmd.getOptionValue(OPT_REVISION_FILE),
cmd.getOptionValue(OPT_METADATA_FILE),
cmd.getOptionValue(OPT_OUTPUT_PATH),
Integer.parseInt(cmd.getOptionValue(OPT_PORT)),
cmd.getOptionValue(OPT_TIRA_PATH),
cmd.getOptionValue(OPT_TIRA_DATASET_NAME)
);
initLogger(config);
try {
Server server = new Server(config);
server.start();
}
finally {
closeLogger();
}
}
private static CommandLine parseArgs(String[] args){
Options options = new Options();
Option input = new Option(OPT_REVISION_FILE, OPT_REVISION_FILE_LONG,
true, OPT_REVISION_FILE_DESC);
input.setRequired(true);
options.addOption(input);
Option metadata = new Option(OPT_METADATA_FILE, OPT_METADATA_FILE_LONG,
true, OPT_METADATA_FILE_DESC);
metadata.setRequired(true);
options.addOption(metadata);
Option outputPath = new Option(OPT_OUTPUT_PATH, OPT_OUTPUT_PATH_LONG,
true, OPT_OUTPUT_PATH_DESC);
outputPath.setRequired(true);
options.addOption(outputPath);
Option port = new Option(OPT_PORT, OPT_PORT_LONG, true, OPT_PORT_DESC);
port.setRequired(true);
options.addOption(port);
Option tiraPath = new Option(OPT_TIRA_PATH, OPT_TIRA_PATH_LONG, true,
OPT_TIRA_PATH_DESC);
tiraPath.setRequired(false);
options.addOption(tiraPath);
Option tiraDatasetName = new Option(OPT_TIRA_DATASET_NAME,
OPT_TIRA_DATASET_NAME_LONG, true, OPT_TIRA_DATASET_NAME_DESC);
tiraDatasetName.setRequired(false);
options.addOption(tiraDatasetName);
CommandLineParser parser = new DefaultParser();
HelpFormatter formatter = new HelpFormatter();
CommandLine cmd = null;
try {
cmd = parser.parse(options, args);
} catch (ParseException e) {
System.out.println(e.getMessage());
formatter.printHelp(WSDM_CUP_2017_DATA_SERVER, options);
System.exit(1);
}
return cmd;
}
public static void initLogger(Configuration config){
logContext = (LoggerContext) LoggerFactory.getILoggerFactory();
Encoder<ILoggingEvent> encoder = buildEncoder();
ConsoleAppender<ILoggingEvent> consoleAppender =
new ConsoleAppender<ILoggingEvent>();
consoleAppender.setContext(logContext);
consoleAppender.setName("console");
consoleAppender.setEncoder(encoder);
consoleAppender.start();
AsyncAppender asyncConsoleAppender =
buildAsyncAppender(consoleAppender);
encoder = buildEncoder();
FileAppender<ILoggingEvent> fileAppender =
new FileAppender<ILoggingEvent>();
fileAppender.setContext(logContext);
fileAppender.setEncoder(encoder);
fileAppender.setFile(getLogFile(config).toString());
fileAppender.setAppend(false);
fileAppender.start();
AsyncAppender asyncFileAppender = buildAsyncAppender(fileAppender);
SiftingAppender siftingAppender = buildSiftingAppender(config);
AsyncAppender asyncSiftingAppender =
buildAsyncAppender(siftingAppender);
Logger logger =
logContext.getLogger(
ch.qos.logback.classic.Logger.ROOT_LOGGER_NAME);
logger.detachAndStopAllAppenders();
logger.addAppender(asyncConsoleAppender);
logger.addAppender(asyncFileAppender);
logger.addAppender(asyncSiftingAppender);
}
private static Encoder<ILoggingEvent> buildEncoder() {
PatternLayoutEncoder encoder = new PatternLayoutEncoder();
encoder.setContext(logContext);
encoder.setCharset(Charset.forName(UTF_8));
encoder.setPattern(LOG_PATTERN);
encoder.start();
return encoder;
}
private static AsyncAppender buildAsyncAppender(
Appender<ILoggingEvent> appender) {
AsyncAppender asyncAppender = new AsyncAppender();
asyncAppender.setContext(logContext);
asyncAppender.addAppender(appender);
asyncAppender.setQueueSize(1024);
asyncAppender.setDiscardingThreshold(0);
asyncAppender.setMaxFlushTime(0);
asyncAppender.start();
return asyncAppender;
}
private static SiftingAppender buildSiftingAppender(Configuration config) {
SiftingAppender siftingAppender = new ClosingSiftingAppender();
siftingAppender.setName("SIFT");
siftingAppender.setContext(logContext);
// Setting timeout to either 0 or unbounded, causes lost log messages.
// Hence, we set it to a reasonable value.
siftingAppender.setTimeout(STALE_APPENDER_TIMEOUT);
MDCBasedDiscriminator discriminator = new MDCBasedDiscriminator();
discriminator.setKey(RequestHandler.MDC_LOG_FILE_KEY);
discriminator.setDefaultValue(
getLogFileForToken(
config.getOutputPath(),
config.getPort(),
"Server")
.getAbsolutePath());
discriminator.start();
siftingAppender.setDiscriminator(discriminator);
siftingAppender.setAppenderFactory(
new AppenderFactory<ILoggingEvent>() {
@Override
public Appender<ILoggingEvent> buildAppender(
Context context, String discriminatingValue)
throws JoranException {
Encoder<ILoggingEvent> encoder = buildEncoder();
FileAppender<ILoggingEvent> fileAppender =
new FileAppender<ILoggingEvent>();
fileAppender.setContext(logContext);
fileAppender.setEncoder(encoder);
fileAppender.setFile(discriminatingValue);
fileAppender.setAppend(false);
fileAppender.start();
return fileAppender;
}
});
siftingAppender.start();
return siftingAppender;
}
private static void closeLogger() {
logContext.stop();
}
private static File getLogFile(Configuration config) {
return getLogFileForToken(
config.getOutputPath(), config.getPort(), null);
}
public static File getLogFileForToken(
File dir, int port, String accessToken) {
String logFileName = getLogFileName(port, accessToken);
File logFile = new File(dir, logFileName).getAbsoluteFile();
return logFile;
}
private static String getLogFileName(int port, String accessToken) {
try {
String host;
host = InetAddress.getLocalHost().getHostName();
String filename = host + "_" + port;
if (accessToken == null) {
filename += EXT_LOG;
} else {
filename += "_" + accessToken + EXT_LOG;
}
return filename;
} catch (UnknownHostException e) {
throw new RuntimeException(e);
}
}
}
// Workaround for bug in Logback (cf. http://jira.qos.ch/browse/LOGBACK-1066)
class ClosingSiftingAppender extends SiftingAppender {
@Override
protected void append(ILoggingEvent event) {
super.append(event);
if (eventMarksEndOfLife(event)) {
getAppenderTracker().removeStaleComponents(Long.MAX_VALUE);
}
}
}
| 8,706 | 29.128028 | 77 | java |
wsdmcup17-data-server | wsdmcup17-data-server-master/src/main/java/org/wsdmcup17/dataserver/Multiplexer.java | package org.wsdmcup17.dataserver;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Map;
import java.util.concurrent.BlockingQueue;
import org.apache.commons.io.output.CloseShieldOutputStream;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.slf4j.MDC;
import org.wsdmcup17.dataserver.result.Result;
import org.wsdmcup17.dataserver.util.BinaryItem;
import org.wsdmcup17.dataserver.util.SynchronizedBoundedBlockingMapQueue;
public class Multiplexer implements Runnable {
private Map<String,String> contextMap;
private OutputStream dataStreamPlain;
BlockingQueue<BinaryItem>
revisionQueue,
metadataQueue;
private SynchronizedBoundedBlockingMapQueue<Long, Result> mapQueue;
private static final Logger LOG = LoggerFactory.getLogger(Multiplexer.class);
private static final String
LOG_MSG_END_OF_DOCUMENT = "XML document completely send",
LOG_MSG_SENDING_REVISION_AT_QUEUE_SIZE =
"Sending revision %s (queue size %d)";
private long lastMillis = 0;
private static final int
DELAY = 10000;
public Multiplexer(Map<String,String> contextMap,
OutputStream dataStreamPlain,
BlockingQueue<BinaryItem> revisionQueue,
BlockingQueue<BinaryItem> metaDataQueue,
SynchronizedBoundedBlockingMapQueue<Long, Result> mapQueue) {
this.contextMap = contextMap;
this.dataStreamPlain = dataStreamPlain;
this.revisionQueue = revisionQueue;
this.metadataQueue = metaDataQueue;
this.mapQueue = mapQueue;
}
@Override
public void run() {
MDC.setContextMap(contextMap);
try {
sendData(dataStreamPlain);
} catch (InterruptedException | IOException e) {
Thread.currentThread().interrupt();
LOG.error("", e);
throw new RuntimeException(e);
}
}
private void sendData(OutputStream dataStreamPlain)
throws InterruptedException, IOException {
try(
// Closing the output stream would result in closing the socket. We
// prevent this because we may still receive data from the client.
OutputStream dataStreamShielded =
new CloseShieldOutputStream(dataStreamPlain);
DataOutputStream dataStream =
new DataOutputStream(dataStreamShielded);
){
sendData(dataStream);
}
}
private void sendData(DataOutputStream dataStream)
throws InterruptedException, IOException {
while (!Thread.currentThread().isInterrupted()) {
BinaryItem revision = revisionQueue.take();
BinaryItem metadata = metadataQueue.take();
long revisionId = revision.getRevisionId();
if (revisionId == Long.MAX_VALUE) {
LOG.debug(LOG_MSG_END_OF_DOCUMENT);
break;
}
else {
if (System.currentTimeMillis() - lastMillis > DELAY) {
LOG.debug(String.format(
LOG_MSG_SENDING_REVISION_AT_QUEUE_SIZE, revisionId,
mapQueue.size()));
lastMillis = System.currentTimeMillis();
}
Result result = new Result(revisionId, null);
mapQueue.put(revision.getRevisionId(), result);
sendItem(metadata, dataStream);
sendItem(revision, dataStream);
}
}
}
private void sendItem(BinaryItem item, DataOutputStream dataStream)
throws IOException {
dataStream.writeInt(item.getBytes().length);
dataStream.write(item.getBytes(), 0, item.getBytes().length);
}
}
| 3,244 | 28.234234 | 78 | java |
wsdmcup17-data-server | wsdmcup17-data-server-master/src/main/java/org/wsdmcup17/dataserver/RequestHandler.java | package org.wsdmcup17.dataserver;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FilenameFilter;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.net.InetAddress;
import java.net.Socket;
import java.util.List;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
import java.util.regex.Pattern;
import org.apache.commons.csv.CSVPrinter;
import org.apache.commons.io.FileUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.slf4j.MDC;
import org.wsdmcup17.dataserver.metadata.MetadataProvider;
import org.wsdmcup17.dataserver.result.Result;
import org.wsdmcup17.dataserver.result.ResultParser;
import org.wsdmcup17.dataserver.result.ResultPrinter;
import org.wsdmcup17.dataserver.result.ResultRecorder;
import org.wsdmcup17.dataserver.revision.RevisionProvider;
import org.wsdmcup17.dataserver.util.BinaryItem;
import org.wsdmcup17.dataserver.util.NonBlockingLineBufferedInputStream;
import org.wsdmcup17.dataserver.util.SynchronizedBoundedBlockingMapQueue;
import static ch.qos.logback.classic.ClassicConstants.FINALIZE_SESSION_MARKER;
public class RequestHandler implements Runnable {
private static final Logger
LOG = LoggerFactory.getLogger(RequestHandler.class);
public static final String
MDC_ACCESS_TOKEN_KEY = "accessToken",
MDC_LOG_FILE_KEY = "logFile";
private static final String
UUID_PATTERN = "^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$",
TIRA_VM_STATE_PATH = "state/virtual-machines",
TIRA_CLIENT_IP_PREFIX = "141.54",
TIRA_RUN_DIR_PATTERN = "data/runs/%s/%s/%s/",
TIRA_PROTOTEXT_NAME = "run.prototext",
LOG_MSG_CONNECTED_TO = "Connected to %s.",
ERROR_MSG_INVALID_TOKEN = "Invalid access token: %s",
ERROR_MSG_INVALID_CLIENT = "Invalid client IP: %s",
THREAD_NAME_REVISION_PROVIDER = "%s: Revision Provider",
THREAD_NAME_METADATA_PROVIDER = "%s: Metadata Provider",
THREAD_NAME_RESULT_RECORDER = "%s: Result Recorder",
THREAD_NAME_MULTIPLEXER = "%s: Multiplexer",
UTF_8 = "UTF-8",
EXT_CSV = ".csv",
EXT_SANDBOXED = ".sandboxed";
private static final int
BACKPRESSURE_WINDOW = 16,
REVISIONS_TO_BUFFER = 128,
STREAM_BUFFER_SIZE = 10000;
private Configuration config;
private BlockingQueue<BinaryItem>
revisionQueue = new ArrayBlockingQueue<>(REVISIONS_TO_BUFFER),
metadataQueue = new ArrayBlockingQueue<>(REVISIONS_TO_BUFFER);
private SynchronizedBoundedBlockingMapQueue<Long, Result>
mapQueue = new SynchronizedBoundedBlockingMapQueue<>(
BACKPRESSURE_WINDOW);
private Socket clientSocket;
private String accessToken;
public RequestHandler(Configuration config, Socket clientSocket) {
this.config = config;
this.clientSocket = clientSocket;
}
@Override
public void run() {
try (
InputStream resultStreamPlain = clientSocket.getInputStream();
OutputStream dataStreamPlain = clientSocket.getOutputStream();
) {
InetAddress clientIP = clientSocket.getInetAddress();
checkClientValidity(clientIP);
LOG.info(String.format(LOG_MSG_CONNECTED_TO, clientIP));
handleRequest(resultStreamPlain, dataStreamPlain);
}
catch (IOException | InterruptedException e) {
Thread.currentThread().interrupt();
LOG.error("", e);
throw new RuntimeException(e);
}
finally {
try {
LOG.debug("Closing socket and freeing memory...");
clientSocket.close();
revisionQueue = null;
metadataQueue = null;
mapQueue = null;
// Several calls are necessary to free heap space
System.gc();
System.gc();
System.gc();
for (int i=0; i<6;i++) {
try {
Thread.sleep(10*1000);
} catch (InterruptedException e) {
LOG.error("", e);
}
System.gc();
}
}
catch (IOException e) {
LOG.error("", e);
throw new RuntimeException(e);
}
}
}
public void handleRequest(
InputStream resultStreamPlain, OutputStream dataStreamPlain
) throws InterruptedException, IOException {
try (
NonBlockingLineBufferedInputStream resultStream =
new NonBlockingLineBufferedInputStream(
resultStreamPlain, STREAM_BUFFER_SIZE);
){
String accessToken = resultStream.readLine();
boolean tokenValid = checkTokenValidity(accessToken);
if (!tokenValid){
String e = String.format(ERROR_MSG_INVALID_TOKEN, accessToken);
throw new Error(e);
}
this.accessToken = accessToken;
MDC.put(MDC_ACCESS_TOKEN_KEY, accessToken);
MDC.put(MDC_LOG_FILE_KEY,
Main.getLogFileForToken(
getRunDir(accessToken),
config.getPort(),
accessToken).getPath());
LOG.info("Handling request for token " + accessToken + "...");
try {
File outputFile = getOutputFile(accessToken);
handleRequest(resultStream, dataStreamPlain, outputFile);
} finally {
LOG.info("Handling request for token "
+ accessToken + "...done.");
LOG.info(FINALIZE_SESSION_MARKER, "Finalize logger...");
MDC.remove(MDC_ACCESS_TOKEN_KEY);
}
}
}
public boolean checkClientValidity(InetAddress clientIP) throws Error {
if (!config.isInProductionMode() ||
clientIP.getHostAddress().startsWith(TIRA_CLIENT_IP_PREFIX)) {
return true;
}
String ipAddress = clientIP.getHostAddress();
String e = String.format(ERROR_MSG_INVALID_CLIENT, ipAddress);
throw new Error(e);
}
private boolean checkTokenValidity(String accessToken) throws IOException {
if (!config.isInProductionMode()) return true;
if (Pattern.matches(UUID_PATTERN, accessToken) &&
!getOutputFile(accessToken).exists() &&
isTiraRunInProgress(accessToken)
) {
return true;
}
else {
return false;
}
}
private boolean isTiraRunInProgress(String accessToken) throws IOException {
return getRunDir(accessToken) != null;
}
private File getRunDir(String accessToken) throws IOException {
if (!config.isInProductionMode()) return config.getOutputPath();
File tiraPath = config.getTiraPath();
File vmStates = new File(tiraPath, TIRA_VM_STATE_PATH);
File[] stateFiles = vmStates.listFiles(new FilenameFilter() {
@Override
public boolean accept(File dir, String name) {
return name.endsWith(EXT_SANDBOXED);
}
});
String datasetName = config.getTiraDatasetName();
for (File stateFile : stateFiles) {
String filename = stateFile.getName();
String username = filename.substring(1, filename.indexOf('-'));
List<String> lines = FileUtils.readLines(stateFile, UTF_8);
if (lines.isEmpty()) continue;
String runId = lines.get(0).split("=")[1].trim();
File runDir = new File(tiraPath, String.format(
TIRA_RUN_DIR_PATTERN, datasetName, username, runId));
File runPrototext = new File(runDir, TIRA_PROTOTEXT_NAME);
if (!runPrototext.exists()) continue;
String contents = FileUtils.readFileToString(runPrototext, UTF_8);
if (contents.contains(accessToken)) {
return runDir;
}
}
return null;
}
private void handleRequest(
NonBlockingLineBufferedInputStream resultStream,
OutputStream dataStreamPlain, File outputFile
) throws InterruptedException, IOException {
try(
OutputStream fileOutputStream = new FileOutputStream(outputFile);
Writer writer = new OutputStreamWriter(fileOutputStream, UTF_8);
CSVPrinter csvPrinter =
new CSVPrinter(writer, ResultParser.CSV_FORMAT);
) {
ThreadGroup threadGroup =
new RequestHandlerThreadGroup(accessToken);
Thread revisionThread = createRevisionProviderThread(threadGroup);
Thread metadataThread = createMetadataProviderThread(threadGroup);
Thread resultRecorderThread =
createResultRecorderThread(
threadGroup, resultStream, csvPrinter);
Thread multiplexerThread =
createMultiplexerThread(threadGroup, dataStreamPlain);
multiplexerThread.join();
revisionThread.join();
metadataThread.interrupt();
metadataThread.join();
clientSocket.shutdownOutput();
resultRecorderThread.join();
}
}
private Thread createRevisionProviderThread(ThreadGroup threadGroup) {
RevisionProvider revisionProvider =
new RevisionProvider(MDC.getCopyOfContextMap(),
threadGroup, revisionQueue, config.getRevisionFile());
Thread revisionThread =
new Thread(threadGroup, revisionProvider,
String.format(THREAD_NAME_REVISION_PROVIDER, accessToken));
revisionThread.start();
return revisionThread;
}
private Thread createMetadataProviderThread(ThreadGroup threadGroup)
throws InterruptedException {
BinaryItem firstRevision = null;
while (firstRevision == null){
firstRevision = revisionQueue.peek();
Thread.sleep(100);
}
long revisionId = firstRevision.getRevisionId();
File metadataFile = config.getMetadataFile();
MetadataProvider metadataProvider =
new MetadataProvider(MDC.getCopyOfContextMap(),
metadataQueue, metadataFile, revisionId);
Thread metaThread =
new Thread(threadGroup, metadataProvider,
String.format(THREAD_NAME_METADATA_PROVIDER, accessToken));
metaThread.start();
return metaThread;
}
private Thread createResultRecorderThread(
ThreadGroup threadGroup,
NonBlockingLineBufferedInputStream resultStream, CSVPrinter csvPrinter
) {
ResultParser parser = new ResultParser(resultStream);
ResultPrinter printer = new ResultPrinter(csvPrinter);
ResultRecorder resultReceiver =
new ResultRecorder(MDC.getCopyOfContextMap(),
mapQueue, parser, printer);
Thread resultReceiverThread =
new Thread(threadGroup, resultReceiver,
String.format(THREAD_NAME_RESULT_RECORDER, accessToken));
resultReceiverThread.start();
return resultReceiverThread;
}
private Thread createMultiplexerThread(
ThreadGroup threadGroup, OutputStream dataStreamPlain) {
Multiplexer multiplexer = new Multiplexer(MDC.getCopyOfContextMap(),
dataStreamPlain, revisionQueue, metadataQueue, mapQueue);
Thread multiplexerThread =
new Thread(threadGroup, multiplexer,
String.format(THREAD_NAME_MULTIPLEXER, accessToken));
multiplexerThread.start();
return multiplexerThread;
}
private File getOutputFile(String accessToken) {
String filename = accessToken + EXT_CSV;
return new File(config.getOutputPath(), filename);
}
class RequestHandlerThreadGroup extends ThreadGroup{
public RequestHandlerThreadGroup(String name) {
super(name);
}
@Override
public void uncaughtException(Thread t, Throwable e) {
LOG.error("Uncaught Exception in Thread " + t.getName(), e);
Thread[] threads = new Thread[this.activeCount()];
this.enumerate(threads);
for (Thread thread: threads){
thread.interrupt();
}
}
}
}
| 10,696 | 30.83631 | 93 | java |
wsdmcup17-data-server | wsdmcup17-data-server-master/src/main/java/org/wsdmcup17/dataserver/Server.java | package org.wsdmcup17.dataserver;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class Server {
private static final Logger
LOG = LoggerFactory.getLogger(Server.class);
private static final String
LOG_MSG_LISTENING_ON = "Listening on port %s.";
private static final int
PARALLELISM = 100;
private Configuration config;
public Server(Configuration config) {
this.config = config;
}
void start() throws UnknownHostException {
int port = config.getPort();
LOG.info(String.format(LOG_MSG_LISTENING_ON, port));
ExecutorService es = Executors.newWorkStealingPool(PARALLELISM);
try (ServerSocket serverSocket = new ServerSocket(port)) {
while (true) {
Socket clientSocket = serverSocket.accept();
es.execute(new RequestHandler(config, clientSocket));
}
}
catch (Throwable e) {
LOG.error("", e);
}
finally {
es.shutdown();
}
}
}
| 1,080 | 22 | 66 | java |
wsdmcup17-data-server | wsdmcup17-data-server-master/src/main/java/org/wsdmcup17/dataserver/metadata/MetadataParser.java | package org.wsdmcup17.dataserver.metadata;
import java.io.InputStream;
import org.wsdmcup17.dataserver.util.BinaryItem;
import org.wsdmcup17.dataserver.util.ItemProcessor;
import org.wsdmcup17.dataserver.util.LineParser;
/**
* Parses a CSV file containing Wikidata metadata and creates a
* {@link BinaryItem} for every revision. The items are forwarded to the given
* {@link ItemProcessor}.
*/
public class MetadataParser extends LineParser {
private boolean isFirstLine = true;
public MetadataParser(ItemProcessor processor, InputStream inputStream){
super(processor, inputStream);
}
@Override
protected void consumeLine(String line) {
if (line == null){ // end of file
return;
}
if (isFirstLine) {
isFirstLine = false;
}
else {
curRevisionId = Long.valueOf(line.substring(0, line.indexOf(',')));
endItem();
processLastItem();
}
}
}
| 887 | 21.769231 | 78 | java |
wsdmcup17-data-server | wsdmcup17-data-server-master/src/main/java/org/wsdmcup17/dataserver/metadata/MetadataProvider.java | package org.wsdmcup17.dataserver.metadata;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.Map;
import java.util.concurrent.BlockingQueue;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.slf4j.MDC;
import org.wsdmcup17.dataserver.util.BinaryItem;
import org.wsdmcup17.dataserver.util.FilterProcessor;
import org.wsdmcup17.dataserver.util.ItemProcessor;
import org.wsdmcup17.dataserver.util.QueueProcessor;
import org.wsdmcup17.dataserver.util.SevenZInputStream;
/**
* Thread reading meta data from a file, parsing the data and putting it into a
* queue.
*/
public class MetadataProvider implements Runnable {
private static final Logger
LOG = LoggerFactory.getLogger(MetadataProvider.class);
Map<String,String> contextMap;
private BlockingQueue<BinaryItem> queue;
private File file;
private long firstRevision;
private MetadataParser parser;
public MetadataProvider(Map<String,String> contextMap,
BlockingQueue<BinaryItem> queue, File file, long firstRevision) {
this.contextMap = contextMap;
this.queue = queue;
this.file = file;
this.firstRevision = firstRevision;
}
@Override
public void run() {
MDC.setContextMap(contextMap);
ItemProcessor nextProcessor = new QueueProcessor(queue);
nextProcessor = new FilterProcessor(nextProcessor, firstRevision);
try (InputStream inputStream = new SevenZInputStream(file)) {
parser = new MetadataParser(nextProcessor, inputStream);
parser.consumeFile();
}
catch (IOException e) {
LOG.error("", e);
throw new RuntimeException(e);
}
}
public void stop(){
parser.stop();
}
}
| 1,650 | 26.065574 | 79 | java |
wsdmcup17-data-server | wsdmcup17-data-server-master/src/main/java/org/wsdmcup17/dataserver/result/Result.java | package org.wsdmcup17.dataserver.result;
/**
* The vandalism score for a given revision id.
*/
public class Result {
private long revisionId;
private Float score;
public Result(long revisionId, Float score) {
this.revisionId = revisionId;
this.score = score;
}
public long getRevisionId() {
return revisionId;
}
public Float getScore() {
return score;
}
public void setScore(Float score) {
this.score = score;
}
}
| 448 | 15.035714 | 47 | java |
wsdmcup17-data-server | wsdmcup17-data-server-master/src/main/java/org/wsdmcup17/dataserver/result/ResultParser.java | package org.wsdmcup17.dataserver.result;
import java.io.IOException;
import org.apache.commons.csv.CSVFormat;
import org.apache.commons.csv.CSVParser;
import org.apache.commons.csv.CSVRecord;
import org.wsdmcup17.dataserver.util.NonBlockingLineBufferedInputStream;
/**
* Parses the scoring results provided in CSV format and converts them to
* {@link Result} objects.
*/
public class ResultParser {
private static final String
ERROR_MSG_WRONG_HEADER = "Wrong header",
ERROR_MSG_WRONG_NUMBER_OF_COLUMNS = "Wrong number of columns: %d",
VANDALISM_SCORE = "VANDALISM_SCORE",
REVISION_ID = "REVISION_ID";
public static final String[]
RESULT_CSV_HEADER = { REVISION_ID, VANDALISM_SCORE };
public static final CSVFormat
CSV_FORMAT = CSVFormat.RFC4180.withHeader(RESULT_CSV_HEADER);
private NonBlockingLineBufferedInputStream lineInputStream;
private boolean isFirstRow = true;
public ResultParser(NonBlockingLineBufferedInputStream lineInputStream) {
this.lineInputStream = lineInputStream;
}
public Result parseResult() throws IOException {
if (isFirstRow) {
String line = lineInputStream.readLine();
checkHeader(line);
isFirstRow = false;
}
String line = lineInputStream.readLine();
if (line == null) {
return null;
}
else {
return parseLine(line);
}
}
private void checkHeader(String line) throws IOException {
CSVRecord csvRecord = parseLineRecord(line);
int size = csvRecord.size();
if(size != 2) {
String e = String.format(ERROR_MSG_WRONG_NUMBER_OF_COLUMNS, size);
throw new IOException(e);
}
if (!RESULT_CSV_HEADER[0].equals(csvRecord.get(RESULT_CSV_HEADER[0])) ||
!RESULT_CSV_HEADER[1].equals(csvRecord.get(RESULT_CSV_HEADER[1]))) {
throw new IOException(ERROR_MSG_WRONG_HEADER);
}
}
private CSVRecord parseLineRecord(String line) throws IOException {
CSVParser parser = CSVParser.parse(line, CSV_FORMAT);
return parser.getRecords().get(0);
}
public Result parseLine(String line) throws IOException {
CSVRecord csvRecord = parseLineRecord(line);
long revisionId = Long.parseLong(csvRecord.get(REVISION_ID));
float score = Float.parseFloat(csvRecord.get(VANDALISM_SCORE));
return new Result(revisionId, score);
}
}
| 2,232 | 28.773333 | 74 | java |
wsdmcup17-data-server | wsdmcup17-data-server-master/src/main/java/org/wsdmcup17/dataserver/result/ResultPrinter.java | package org.wsdmcup17.dataserver.result;
import java.io.IOException;
import org.apache.commons.csv.CSVPrinter;
/**
* Writes a {@link Result} to a CSV file.
*/
public class ResultPrinter {
CSVPrinter csvPrinter;
public ResultPrinter(CSVPrinter csvPrinter) {
this.csvPrinter = csvPrinter;
}
public void printResult(Result scoringResult) throws IOException {
csvPrinter.print(scoringResult.getRevisionId());
csvPrinter.print(scoringResult.getScore());
csvPrinter.println();
}
}
| 500 | 19.875 | 67 | java |
wsdmcup17-data-server | wsdmcup17-data-server-master/src/main/java/org/wsdmcup17/dataserver/result/ResultRecorder.java | package org.wsdmcup17.dataserver.result;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.slf4j.MDC;
import org.wsdmcup17.dataserver.util.SynchronizedBoundedBlockingMapQueue;
/**
* Thread parsing and validating scoring results.
*/
public class ResultRecorder implements Runnable {
private static final String
ERROR_MSG_MISSING_REVISION_SCORES = "Missing revision scores: %s",
ERROR_MSG_DUPLICATE_REVISION = "Duplicate revision: %d",
ERROR_MSG_UNEXPECTED_REVISION = "Unexpected revision: %d",
LOG_MSG_WRITING_REVISION_RESULT_AT_QUEUE_SIZE =
"Writing revision result %s (queue size %d)";
private static final Logger
LOG = LoggerFactory.getLogger(ResultRecorder.class);
private static final int
DELAY = 10000;
private Map<String,String> contextMap;
private ResultParser resultParser;
private ResultPrinter resultPrinter;
private SynchronizedBoundedBlockingMapQueue<Long, Result> mapQueue;
private long lastMillis = 0;
public ResultRecorder(Map<String,String> contextMap,
SynchronizedBoundedBlockingMapQueue<Long, Result> mapQueue,
ResultParser resultParser, ResultPrinter resultPrinter
) {
this.contextMap = contextMap;
this.mapQueue = mapQueue;
this.resultParser = resultParser;
this.resultPrinter = resultPrinter;
}
public void run() {
MDC.setContextMap(contextMap);
try {
while (!Thread.currentThread().isInterrupted()) {
Result parsedResult = resultParser.parseResult();
if (parsedResult != null) {
consumeResult(parsedResult);
}
else {
if (mapQueue.size() > 0) {
String e = createErrorMsg();
throw new IllegalStateException(e);
}
// The last result has been read and written.
break;
}
}
}
catch (Throwable e) {
LOG.error("", e);
throw new RuntimeException(e);
}
}
private String createErrorMsg() {
List<Long> missing = new ArrayList<Long>();
while (mapQueue.size() > 0) {
missing.add(mapQueue.peek().getRevisionId());
mapQueue.remove();
}
return String.format(ERROR_MSG_MISSING_REVISION_SCORES, missing);
}
private void consumeResult(Result parsedResult)
throws InterruptedException, IOException {
long revisionId = parsedResult.getRevisionId();
Result queueResult = mapQueue.get(revisionId);
if (queueResult == null) {
String e = String.format(ERROR_MSG_UNEXPECTED_REVISION, revisionId);
throw new IllegalStateException(e);
}
if (queueResult.getScore() != null) {
String e = String.format(ERROR_MSG_DUPLICATE_REVISION, revisionId);
throw new IllegalStateException(e);
}
queueResult.setScore(parsedResult.getScore());
writeResults(mapQueue, resultPrinter);
}
private void writeResults(
SynchronizedBoundedBlockingMapQueue<Long, Result> mapQueue,
ResultPrinter resultPrinter
) throws IOException {
while(true){
Result result = mapQueue.peek();
if (result != null && result.getScore() != null) {
if (System.currentTimeMillis() - lastMillis > DELAY){
LOG.debug(String.format(
LOG_MSG_WRITING_REVISION_RESULT_AT_QUEUE_SIZE,
result.getRevisionId(), mapQueue.size()));
lastMillis = System.currentTimeMillis();
}
resultPrinter.printResult(result);
mapQueue.remove();
}
else {
break;
}
}
}
}
| 3,374 | 27.125 | 73 | java |
wsdmcup17-data-server | wsdmcup17-data-server-master/src/main/java/org/wsdmcup17/dataserver/revision/RevisionParser.java | package org.wsdmcup17.dataserver.revision;
import java.io.InputStream;
import org.wsdmcup17.dataserver.util.BinaryItem;
import org.wsdmcup17.dataserver.util.ItemProcessor;
import org.wsdmcup17.dataserver.util.LineParser;
/**
* Parses a Wikimedia XML file and creates a {@link BinaryItem} for every
* revision. The items are forwarded to the given {@link ItemProcessor}.
*/
public class RevisionParser extends LineParser {
private static final String REVISION_OPENING_TAG = " <revision>";
private static final String REVISION_CLOSING_TAG = " </revision>";
private static final String REVISION_ID_OPENING_TAG = " <id>";
private static final String REVISION_ID_CLOSING_TAG = "</id>";
private enum State {
EXPECT_REVISION, EXPECT_REVISION_ID, EXPECT_REVISION_CLOSING_TAG
}
private State state = State.EXPECT_REVISION;
public RevisionParser(ItemProcessor processor, InputStream inputStream) {
super(processor, inputStream);
}
@Override
protected void consumeLine(String line) {
if (line == null){ // end of file
appendToItem();
processLastItem();
return;
}
switch (state) {
case EXPECT_REVISION:
if (line.equals(REVISION_OPENING_TAG)) {
state = State.EXPECT_REVISION_ID;
processLastItem();
}
break;
case EXPECT_REVISION_ID:
if (line.startsWith(REVISION_ID_OPENING_TAG)) {
String revisionId = getSubstring(
line, REVISION_ID_OPENING_TAG, REVISION_ID_CLOSING_TAG);
curRevisionId = Long.parseLong(revisionId);
state = State.EXPECT_REVISION_CLOSING_TAG;
}
break;
case EXPECT_REVISION_CLOSING_TAG:
if (line.equals(REVISION_CLOSING_TAG)) {
state = State.EXPECT_REVISION;
endItem();
}
break;
default:
break;
}
}
private String getSubstring(String s, String start, String end) {
return s.substring(start.length(), s.length() - end.length());
}
}
| 1,868 | 26.086957 | 74 | java |
wsdmcup17-data-server | wsdmcup17-data-server-master/src/main/java/org/wsdmcup17/dataserver/revision/RevisionProvider.java | package org.wsdmcup17.dataserver.revision;
import java.io.File;
import java.io.InputStream;
import java.util.Map;
import java.util.concurrent.BlockingQueue;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.slf4j.MDC;
import org.wsdmcup17.dataserver.util.AsyncInputStream;
import org.wsdmcup17.dataserver.util.BinaryItem;
import org.wsdmcup17.dataserver.util.QueueProcessor;
import org.wsdmcup17.dataserver.util.SevenZInputStream;
/**
* Thread reading revisions from a file, parsing them and putting them into a
* queue.
*/
public class RevisionProvider implements Runnable {
private static final String REVISION_DECOMPRESSOR =
"%s: Revision Decompressor";
private static final int BUFFER_SIZE = 512 * 1024 * 1024;
private static final Logger LOG = LoggerFactory.getLogger(RevisionProvider.class);
private Map<String,String> contextMap;
private ThreadGroup threadGroup;
private BlockingQueue<BinaryItem> queue;
private File file;
private RevisionParser parser;
public RevisionProvider(Map<String,String> contextMap,
ThreadGroup threadGroup, BlockingQueue<BinaryItem> queue, File file) {
this.contextMap = contextMap;
this.threadGroup = threadGroup;
this.queue = queue;
this.file = file;
}
public void run() {
MDC.setContextMap(contextMap);
try (
InputStream sevenZInput = new SevenZInputStream(file);
InputStream asyncInput = new AsyncInputStream(
threadGroup,
String.format(REVISION_DECOMPRESSOR, threadGroup.getName()),
sevenZInput,
BUFFER_SIZE);
){
parser = new RevisionParser(new QueueProcessor(queue), asyncInput);
parser.consumeFile();
} catch (Throwable e) {
LOG.error("", e);
throw new RuntimeException(e);
}
}
} | 1,726 | 27.311475 | 83 | java |
wsdmcup17-data-server | wsdmcup17-data-server-master/src/main/java/org/wsdmcup17/dataserver/util/AsyncInputStream.java | package org.wsdmcup17.dataserver.util;
import java.io.IOException;
import java.io.InputStream;
import java.io.PipedInputStream;
import java.io.PipedOutputStream;
import org.apache.commons.compress.utils.IOUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* An input stream that splits the processing of the stream into two threads.
*/
public class AsyncInputStream extends PipedInputStream {
private static final Logger
LOG = LoggerFactory.getLogger(AsyncInputStream.class);
private Thread thread;
public AsyncInputStream(
final ThreadGroup threadGroup, String threadName,
InputStream inputStream, int bufferSize
) throws IOException {
super(bufferSize);
final PipedOutputStream pipedOutputStream = new PipedOutputStream();
this.connect(pipedOutputStream);
thread = new Thread(threadGroup, threadName) {
@Override
public void run() {
try {
IOUtils.copy(inputStream, pipedOutputStream);
inputStream.close();
pipedOutputStream.close();
}
catch (Throwable e) {
LOG.error("", e);
throw new RuntimeException(e);
}
}
};
thread.start();
}
public AsyncInputStream(
final String threadName, InputStream inputStream, int bufferSize
) throws IOException {
this(null, threadName, inputStream, bufferSize);
}
@Override
public void close() throws IOException {
super.close();
try {
thread.join();
}
catch (InterruptedException e) {
Thread.currentThread().interrupt();
LOG.error("", e);
throw new RuntimeException(e);
}
}
}
| 1,562 | 23.046154 | 77 | java |
wsdmcup17-data-server | wsdmcup17-data-server-master/src/main/java/org/wsdmcup17/dataserver/util/BinaryItem.java | package org.wsdmcup17.dataserver.util;
/**
* A binary item.
*/
public class BinaryItem {
private long revisionId;
private byte[] bytes;
public BinaryItem(long revisionId, byte[] bytes) {
this.revisionId = revisionId;
this.bytes = bytes;
}
public long getRevisionId() {
return revisionId;
}
public byte[] getBytes() {
return bytes;
}
}
| 359 | 14.652174 | 51 | java |
wsdmcup17-data-server | wsdmcup17-data-server-master/src/main/java/org/wsdmcup17/dataserver/util/FilterProcessor.java | package org.wsdmcup17.dataserver.util;
/**
* Processes a binary item and forwards the event to the next processor if the
* filtering criteria are met (the given <code>firstRevisionId</code> has been
* read).
*/
public class FilterProcessor implements ItemProcessor {
private ItemProcessor processor;
private long firstRevisionId;
private boolean firstRevisionIdRead = false;
public FilterProcessor(ItemProcessor processor, long firstRevisionId) {
this.processor = processor;
this.firstRevisionId = firstRevisionId;
}
@Override
public void processItem(BinaryItem item) {
if (item.getRevisionId() == firstRevisionId) {
firstRevisionIdRead = true;
}
if (firstRevisionIdRead) {
processor.processItem(item);
}
}
}
| 743 | 24.655172 | 78 | java |
wsdmcup17-data-server | wsdmcup17-data-server-master/src/main/java/org/wsdmcup17/dataserver/util/ItemProcessor.java | package org.wsdmcup17.dataserver.util;
/**
* Processes a binary item.
*/
public interface ItemProcessor {
void processItem(BinaryItem item);
}
| 147 | 15.444444 | 38 | java |
wsdmcup17-data-server | wsdmcup17-data-server-master/src/main/java/org/wsdmcup17/dataserver/util/LineParser.java | package org.wsdmcup17.dataserver.util;
import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.nio.charset.StandardCharsets;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.wsdmcup17.dataserver.util.BinaryItem;
import org.wsdmcup17.dataserver.util.ItemProcessor;
/**
* Abstract class for parsing lines of a text file one by one.
*
* A concrete subclass has to implement the {@link #consumeLine(String)} method
* and call the the {@link #processCurItem()} method whenever the processing of
* an item has finished (possibly after having consumed several lines}.
*/
public abstract class LineParser {
private static final Logger LOG = LoggerFactory.getLogger(LineParser.class);
private static final String
LOG_MSG_END_OF_FILE = "end of file reached",
CRLF = "\r\n", // RFC4180 demands the line ending \r\n.
UTF_8 = "UTF-8";
private StringBuilder curString = new StringBuilder();
private ItemProcessor processor;
private InputStream inputStream;
private BinaryItem lastItem = null;
private volatile boolean isStopping;
protected long curRevisionId; // Must be set by subclass.
protected LineParser(ItemProcessor processor, InputStream inputStream) {
this.processor = processor;
this.inputStream = inputStream;
}
public void consumeFile() throws IOException {
try (
Reader reader = new InputStreamReader(inputStream, UTF_8);
BufferedReader bufferedReader = new BufferedReader(reader);
) {
String line;
while ((line = bufferedReader.readLine()) != null &&
!isStopping && !Thread.currentThread().isInterrupted()) {
appendLineToCurItem(line);
consumeLine(line);
}
if (line == null) { // end of file reached
consumeLine(line);
LOG.debug(LOG_MSG_END_OF_FILE);
// send sentinel to indicate end of item stream
curRevisionId = Long.MAX_VALUE;
curString = new StringBuilder();
endItem();
processLastItem();
}
}
}
protected abstract void consumeLine(String line);
/**
* Must be called by subclass at the end of an item.
*/
protected void processLastItem() {
if (lastItem != null){
processor.processItem(lastItem);
lastItem = null;
}
}
protected void endItem() {
byte[] bytes = stringToBytes(curString.toString());
lastItem = new BinaryItem(curRevisionId, bytes);
resetBuffers();
}
protected void appendToItem() {
try {
byte[] bytes = stringToBytes(curString.toString());
// append bytes
ByteArrayOutputStream outputStream = new ByteArrayOutputStream( );
outputStream.write(lastItem.getBytes());
outputStream.write(bytes);
bytes = outputStream.toByteArray();
lastItem = new BinaryItem(lastItem.getRevisionId(), bytes);
resetBuffers();
} catch (IOException e) {
LOG.error("", e);
throw new RuntimeException(e);
}
}
private void appendLineToCurItem(String line) {
curString.append(line);
curString.append(CRLF);
}
private void resetBuffers() {
curRevisionId = -1;
curString = new StringBuilder();
}
private byte[] stringToBytes(String str) {
return curString.toString().getBytes(StandardCharsets.UTF_8);
}
public void stop() {
isStopping = true;
}
}
| 3,313 | 25.301587 | 79 | java |
wsdmcup17-data-server | wsdmcup17-data-server-master/src/main/java/org/wsdmcup17/dataserver/util/NonBlockingLineBufferedInputStream.java | package org.wsdmcup17.dataserver.util;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
/**
* InputStream capable of reading lines without reading ahead, thus avoiding
* blocking.
*/
public class NonBlockingLineBufferedInputStream extends InputStream {
private static final String
ERROR_MSG_LINE_TOO_LONG_FOR_BUFFER = "Line too long for buffer",
ERROR_MSG_INVALID_LINE_ENDING = "Invalid Line Ending ";
private InputStream inputStream;
byte[] lineBuffer;
public NonBlockingLineBufferedInputStream(
InputStream inputStream, int bufferSize
) {
this.inputStream = inputStream;
this.lineBuffer = new byte[bufferSize];
}
@Override
public int read() throws IOException {
return inputStream.read();
}
@Override
public int read(byte[] b) throws IOException {
throw new UnsupportedOperationException();
}
@Override
public int read(byte[] b, int off, int len) throws IOException {
throw new UnsupportedOperationException();
}
@Override
public long skip(long n) throws IOException {
throw new UnsupportedOperationException();
}
@Override
public int available() throws IOException {
throw new UnsupportedOperationException();
}
@Override
public void close() throws IOException {
inputStream.close();
}
@Override
public synchronized void mark(int readlimit) {
throw new UnsupportedOperationException();
}
@Override
public synchronized void reset() throws IOException {
throw new UnsupportedOperationException();
}
@Override
public boolean markSupported() {
return false;
}
public String readLine() throws IOException {
int curPos = 0;
while(true) {
int b = this.read();
if (b == (byte)'\r') {
b = this.read();
if (b != (byte)'\n') {
throw new IOException(ERROR_MSG_INVALID_LINE_ENDING + b);
}
break;
}
else if (b == -1) {
return null;
}
lineBuffer[curPos] = (byte)b;
curPos++;
if (curPos >= lineBuffer.length) {
throw new IOException(ERROR_MSG_LINE_TOO_LONG_FOR_BUFFER);
}
}
return new String(lineBuffer, 0, curPos, StandardCharsets.UTF_8);
}
}
| 2,145 | 20.897959 | 76 | java |
wsdmcup17-data-server | wsdmcup17-data-server-master/src/main/java/org/wsdmcup17/dataserver/util/QueueProcessor.java | package org.wsdmcup17.dataserver.util;
import java.util.concurrent.BlockingQueue;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Puts binary items in a queue.
*/
public class QueueProcessor implements ItemProcessor {
private static final Logger LOG = LoggerFactory.getLogger(QueueProcessor.class);
private static final String
LOG_MSG_THREAD_INTERRUPTED = "Thread interrupted";
private BlockingQueue<BinaryItem> queue;
public QueueProcessor(BlockingQueue<BinaryItem> queue) {
this.queue = queue;
}
@Override
public void processItem(BinaryItem item) {
try{
queue.put(item);
}
catch (InterruptedException e){
// Reset the interrupt flag.
Thread.currentThread().interrupt();
LOG.debug(LOG_MSG_THREAD_INTERRUPTED);
}
}
}
| 778 | 20.054054 | 81 | java |
wsdmcup17-data-server | wsdmcup17-data-server-master/src/main/java/org/wsdmcup17/dataserver/util/SevenZInputStream.java | package org.wsdmcup17.dataserver.util;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import org.apache.commons.compress.archivers.sevenz.SevenZFile;
/**
* A <code>SevenZInputStream</code> obtains input bytes from a compressed 7z
* file in a file system.
*/
public class SevenZInputStream extends InputStream{
private static final String
ERROR_MSG_MULTIPLE_7Z_STREAMS = "Multiple 7z streams.";
private SevenZFile sevenZFile;
public SevenZInputStream(File file) throws IOException {
sevenZFile = new SevenZFile(file);
sevenZFile.getNextEntry();
}
@Override
public int read() throws IOException {
int result = sevenZFile.read();
return result;
}
@Override
public int read(byte[] b) throws IOException {
int numberOfBytesRead = sevenZFile.read(b);
return numberOfBytesRead;
}
@Override
public int read(byte[] b, int off, int len) throws IOException {
int numberOfBytesRead = sevenZFile.read(b, off, len);
return numberOfBytesRead;
}
@Override
public void close() throws IOException {
if (sevenZFile.getNextEntry() != null) {
sevenZFile.close();
throw new IOException(ERROR_MSG_MULTIPLE_7Z_STREAMS);
}
sevenZFile.close();
}
}
| 1,219 | 22.461538 | 76 | java |
wsdmcup17-data-server | wsdmcup17-data-server-master/src/main/java/org/wsdmcup17/dataserver/util/SynchronizedBoundedBlockingMapQueue.java | package org.wsdmcup17.dataserver.util;
import java.util.AbstractMap;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.Map;
import java.util.Map.Entry;
import java.util.NoSuchElementException;
import java.util.Queue;
public class SynchronizedBoundedBlockingMapQueue<K, V> {
private static final String
ERROR_MSG_KEY_ALREADY_IN_QUEUE = "Key already in queue: %s",
ERROR_MSG_KEY_VALUE_MAPPING_MIXED_UP = "Key-values mapping mixed up.",
ERROR_MSG_QUEUE_MAP_SIZE_MISMATCH = "Queue and map size mismatch.";
private Queue<Entry<K, V>> queue = new LinkedList<>();
private Map<K,V> map = new HashMap<K,V>();
private int capacity;
public SynchronizedBoundedBlockingMapQueue(int capacity) {
this.capacity = capacity;
}
/**
* Inserts the specified element into this queue, waiting if necessary for
* space to become available.
*
* Associates the specified value with the specified key in this map. If the
* map previously contained a mapping for the key, the old value is
* replaced.
*
* @param e
* the element to add
* @throws InterruptedException
* if interrupted while waiting
* @throws ClassCastException
* if the class of the specified element prevents it from being
* added to this queue
* @throws NullPointerException
* if the specified element is null
* @throws IllegalArgumentException
* if some property of the specified element prevents it from
* being added to this queue
*/
public synchronized void put (K key, V value) throws InterruptedException {
// Wait until there is sufficient space in the queue.
while(queue.size() >= capacity) {
wait();
}
if (map.containsKey(key)) {
String e = String.format(ERROR_MSG_KEY_ALREADY_IN_QUEUE, key);
throw new IllegalArgumentException(e);
}
queue.add(new AbstractMap.SimpleEntry<K, V>(key, value));
try{
map.put(key, value);
}
catch (ClassCastException | NullPointerException
| IllegalArgumentException e) {
queue.remove(value);
throw e;
}
notifyAll(); // Now the get operation might return the value.
}
/**
* Returns the value to which the specified key is mapped, or blocks until
* this map contains a mapping for the key.
*/
public synchronized V get(K key) throws InterruptedException {
// Wait until the queue contains the key.
while (!map.containsKey(key)){
wait();
}
return map.get(key);
}
/**
* Retrieves, but does not remove, the head of this queue, or returns
* <tt>null</tt> if this queue is empty.
*
* @return the head of this queue, or <tt>null</tt> if this queue is empty
*/
public synchronized V peek() {
Entry<K, V> entry = queue.peek();
if (entry == null) {
return null;
}
else {
return entry.getValue();
}
}
/**
* Retrieves and removes the head of this queue. This method differs from
* {@link #poll poll} only in that it throws an exception if this queue is
* empty.
*
* @return the head of this queue
* @throws NoSuchElementException
* if this queue is empty
*/
public synchronized void remove() {
Entry<K, V> entry = queue.peek();
if (entry != null) {
if (!map.remove(entry.getKey(), entry.getValue())) {
throw new IllegalStateException(
ERROR_MSG_KEY_VALUE_MAPPING_MIXED_UP);
}
queue.remove();
}
notifyAll(); // Now new elements may be put in the queue.
}
/**
* Returns the number of elements in this collection. If this collection
* contains more than <tt>Integer.MAX_VALUE</tt> elements, returns
* <tt>Integer.MAX_VALUE</tt>.
*
* @return the number of elements in this collection
*/
public synchronized int size() {
int result = queue.size();
if (result != map.size()) {
throw new IllegalStateException(ERROR_MSG_QUEUE_MAP_SIZE_MISMATCH);
}
return result;
}
}
| 3,887 | 28.233083 | 77 | java |
Paddle-Lite-develop/lite/api/android/jni/src/com/baidu/paddle/lite/ConfigBase.java | Paddle-Lite-develop/lite/api/android/jni/src/com/baidu/paddle/lite/ConfigBase.java | /* Copyright (c) 2019 PaddlePaddle Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License. */
package com.baidu.paddle.lite;
/**
* Base class for all configurations.
*/
public class ConfigBase {
protected String modelDir;
public String getModelDir() {
return modelDir;
}
public void setModelDir(String modelDir) {
this.modelDir = modelDir;
}
}
| 886 | 26.71875 | 72 | java |
Paddle-Lite-develop/lite/api/android/jni/src/com/baidu/paddle/lite/CxxConfig.java | Paddle-Lite-develop/lite/api/android/jni/src/com/baidu/paddle/lite/CxxConfig.java | /* Copyright (c) 2019 PaddlePaddle Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License. */
package com.baidu.paddle.lite;
/**
* CxxConfig is the configuration for the Full feature predictor.
*/
public class CxxConfig extends ConfigBase {
protected Place[] validPlaces;
public Place[] getValidPlaces() {
return validPlaces;
}
public void setValidPlaces(Place[] validPlaces) {
this.validPlaces = validPlaces;
}
}
| 955 | 29.83871 | 72 | java |
Paddle-Lite-develop/lite/api/android/jni/src/com/baidu/paddle/lite/MobileConfig.java | Paddle-Lite-develop/lite/api/android/jni/src/com/baidu/paddle/lite/MobileConfig.java | /* Copyright (c) 2019 PaddlePaddle Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License. */
package com.baidu.paddle.lite;
/**
* MobileConfig is the config for the light weight predictor, it will skip IR
* optimization or other unnecessary stages.
*/
public class MobileConfig extends ConfigBase {
/**
* Set power mode.
*
* @return
*/
public void setPowerMode(PowerMode powerMode) {
this.powerMode = powerMode;
}
/**
* Returns power mode.
*
* @return power mode
*/
public PowerMode getPowerMode() {
return powerMode;
}
/**
* Set threads num.
*
* @return
*/
public void setThreads(int threads) {
this.threads = threads;
}
/**
* Returns threads num.
*
* @return threads num
*/
public int getThreads() {
return threads;
}
/**
* Returns power mode as enum int value.
*
* @return power mode as enum int value
*/
public int getPowerModeInt() {
return powerMode.value();
}
/**
* Set model from file.
*
* @return
*/
public void setModelFromFile(String modelFile) {
this.liteModelFile = modelFile;
}
/**
* Returns name of model_file.
*
* @return liteModelFile
*/
public String getModelFromFile() {
return liteModelFile;
}
/**
* Set model from buffer.
*
* @return
*/
public void setModelFromBuffer(String modelBuffer) {
this.liteModelBuffer = modelBuffer;
}
/**
* Returns model buffer
*
* @return liteModelBuffer
*/
public String getModelFromBuffer() {
return liteModelBuffer;
}
private PowerMode powerMode = PowerMode.LITE_POWER_HIGH;
private int threads = 1;
private String liteModelFile;
private String liteModelBuffer;
}
| 2,410 | 21.324074 | 77 | java |
Paddle-Lite-develop/lite/api/android/jni/src/com/baidu/paddle/lite/PaddleLiteInitializer.java | Paddle-Lite-develop/lite/api/android/jni/src/com/baidu/paddle/lite/PaddleLiteInitializer.java | package com.baidu.paddle.lite;
/**
* Initializer for PaddleLite. The initialization methods are called by package
* classes only. Public users don't have to call them. Public users can get
* PaddleLite information constants such as JNI lib name in this class.
*/
public class PaddleLiteInitializer {
/** name of C++ JNI lib */
public final static String JNI_LIB_NAME = "paddle_lite_jni";
/**
* loads the C++ JNI lib. We only call it in our package, so it shouldn't be
* visible to public users.
*
* @return true if initialize successfully.
*/
protected static boolean init() {
System.loadLibrary(JNI_LIB_NAME);
return true;
}
}
| 697 | 28.083333 | 80 | java |
Paddle-Lite-develop/lite/api/android/jni/src/com/baidu/paddle/lite/PaddlePredictor.java | Paddle-Lite-develop/lite/api/android/jni/src/com/baidu/paddle/lite/PaddlePredictor.java | /* Copyright (c) 2019 PaddlePaddle Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License. */
package com.baidu.paddle.lite;
/** Java Native Interface (JNI) class for Paddle Lite APIs */
public class PaddlePredictor {
/**
* Java doesn't have pointer. To maintain the life cycle of underneath C++
* PaddlePredictor object, we use a long value to maintain it.
*/
private long cppPaddlePredictorPointer;
/**
* Constructor of a PaddlePredictor.
*
* @param config the input configuration.
*/
public PaddlePredictor(ConfigBase config) {
init(config);
}
/**
* Creates a PaddlePredictor object.
*
* @param config the input configuration.
* @return the PaddlePredictor object, or null if failed to create it.
*/
public static PaddlePredictor createPaddlePredictor(ConfigBase config) {
PaddlePredictor predictor = new PaddlePredictor(config);
return predictor.cppPaddlePredictorPointer == 0L ? null : predictor;
}
/**
* Get offset-th input tensor.
*
* @param offset
* @return the tensor or null if failed to get it.
*/
public Tensor getInput(int offset) {
long cppTensorPointer = getInputCppTensorPointer(offset);
return cppTensorPointer == 0 ? null : new Tensor(cppTensorPointer, /* readOnly = */ false, this);
}
/**
* Get offset-th output tensor.
*
* @param offset
* @return the tensor or null if failed to get it.
*/
public Tensor getOutput(int offset) {
long cppTensorPointer = getOutputCppTensorPointer(offset);
return cppTensorPointer == 0 ? null : new Tensor(cppTensorPointer, /* readOnly = */ true, this);
}
/**
* Get a tensor by name.
*
* @param name the name of the tensor.
* @return the tensor or null if failed to get it.
*/
public Tensor getTensor(String name) {
long cppTensorPointer = getCppTensorPointerByName(name);
return cppTensorPointer == 0 ? null : new Tensor(cppTensorPointer, /* readOnly = */ true, this);
}
/**
* Run the PaddlePredictor.
*
* @return true if run successfully.
*/
public native boolean run();
/**
* Get c++ lib's version information.
*
* @return C++ lib's version information.
*/
public native String getVersion();
/**
* Saves the optimized model. It is available only for {@link CxxConfig}
*
* @param modelDir the path to save the optimized model
* @return true if save successfully. Otherwise returns false.
*/
public native boolean saveOptimizedModel(String modelDir);
/**
* Deletes C++ PaddlePredictor pointer when Java PaddlePredictor object is
* destroyed
*/
@Override
protected void finalize() throws Throwable {
clear();
super.finalize();
}
/**
* Create a C++ PaddlePredictor object based on configuration
*
* @param config the input configuration
* @return true if create successfully
*/
protected boolean init(ConfigBase config) {
if (config instanceof CxxConfig) {
cppPaddlePredictorPointer = newCppPaddlePredictor((CxxConfig) config);
} else if (config instanceof MobileConfig) {
cppPaddlePredictorPointer = newCppPaddlePredictor((MobileConfig) config);
} else {
throw new IllegalArgumentException("Not supported PaddleLite Config type");
}
return cppPaddlePredictorPointer != 0L;
}
/**
* Deletes C++ PaddlePredictor pointer
*
* @return true if deletion success
*/
protected boolean clear() {
boolean result = false;
if (cppPaddlePredictorPointer != 0L) {
result = deleteCppPaddlePredictor(cppPaddlePredictorPointer);
cppPaddlePredictorPointer = 0L;
}
return result;
}
/**
* Gets offset-th input tensor pointer at C++ side.
*
* @param offset
* @return a long value which is reinterpret_cast of the C++ pointer.
*/
private native long getInputCppTensorPointer(int offset);
/**
* Gets offset-th output tensor pointer at C++ side.
*
* @param offset
* @return a long value which is reinterpret_cast of the C++ pointer.
*/
private native long getOutputCppTensorPointer(int offset);
/**
* Gets tensor pointer at C++ side by name.
*
* @param name the name of the tensor.
* @return a long value which is reinterpret_cast of the C++ pointer.
*/
private native long getCppTensorPointerByName(String name);
/**
* Creates a new C++ PaddlePredcitor object using CxxConfig, returns the
* reinterpret_cast value of the C++ pointer which points to C++
* PaddlePredictor.
*
* @param config
* @return a long value which is reinterpret_cast of the C++ pointer.
*/
private native long newCppPaddlePredictor(CxxConfig config);
/**
* Creates a new C++ PaddlePredcitor object using Mobile, returns the
* reinterpret_cast value of the C++ pointer which points to C++
* PaddlePredictor.
*
* @param config
* @return a long value which is reinterpret_cast of the C++ pointer.
*/
private native long newCppPaddlePredictor(MobileConfig config);
/**
* Delete C++ PaddlePredictor object pointed by the input pointer, which is
* presented by a long value.
*
* @param nativePointer a long value which is reinterpret_cast of the C++
* pointer.
* @return true if deletion success.
*/
private native boolean deleteCppPaddlePredictor(long nativePointer);
/* Initializes at the beginning */
static {
PaddleLiteInitializer.init();
}
}
| 6,341 | 30.71 | 105 | java |
Paddle-Lite-develop/lite/api/android/jni/src/com/baidu/paddle/lite/Place.java | Paddle-Lite-develop/lite/api/android/jni/src/com/baidu/paddle/lite/Place.java | /* Copyright (c) 2019 PaddlePaddle Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License. */
package com.baidu.paddle.lite;
/**
* Place specifies the execution context of a Kernel or input/output for a
* kernel. It is used to make the analysis of the MIR more clear and accurate.
*/
public class Place {
/** Place hardware target type. */
public enum TargetType {
UNKNOWN(0), HOST(1), X86(2), CUDA(3), ARM(4), OPEN_CL(5), FPGA(7), ANY(6);
public final int value;
private TargetType(int value) {
this.value = value;
}
}
/** Place precision type */
public enum PrecisionType {
UNKNOWN(0), FLOAT(1), INT8(2), FP16(5), INT32(3), ANY(4), BOOL(6);
public final int value;
private PrecisionType(int value) {
this.value = value;
}
}
/** Place data layout type */
public enum DataLayoutType {
UNKNOWN(0), NCHW(1), NHWC(3), ANY(2);
public final int value;
private DataLayoutType(int value) {
this.value = value;
}
}
private TargetType target;
private PrecisionType precision;
private DataLayoutType layout;
private int device;
public Place() {
target = TargetType.UNKNOWN;
precision = PrecisionType.UNKNOWN;
layout = DataLayoutType.UNKNOWN;
device = 0;
}
public Place(TargetType target) {
this(target, PrecisionType.FLOAT);
}
public Place(TargetType target, PrecisionType precision) {
this(target, precision, DataLayoutType.NCHW);
}
public Place(TargetType target, PrecisionType precision, DataLayoutType layout) {
this(target, precision, layout, 0);
}
public Place(TargetType target, PrecisionType precision, DataLayoutType layout, int device) {
this.target = target;
this.precision = precision;
this.layout = layout;
this.device = device;
}
public boolean isValid() {
return target != TargetType.UNKNOWN && precision != PrecisionType.UNKNOWN && layout != DataLayoutType.UNKNOWN;
}
public TargetType getTarget() {
return target;
}
public void setTarget(TargetType target) {
this.target = target;
}
public PrecisionType getPrecision() {
return precision;
}
public void setPrecision(PrecisionType precision) {
this.precision = precision;
}
public DataLayoutType getLayout() {
return layout;
}
public void setLayout(DataLayoutType layout) {
this.layout = layout;
}
public int getDevice() {
return device;
}
public void setDevice(int device) {
this.device = device;
}
/**
* Returns hardware target as enum int value.
*
* @return hardware target as enum int value
*/
public int getTargetInt() {
return target.value;
}
/**
* Returns precision target as enum int value.
*
* @return precision as enum int value
*/
public int getPrecisionInt() {
return precision.value;
}
/**
* Returns data layout as enum int value.
*
* @return data layout as enum int value
*/
public int getDataLayoutInt() {
return layout.value;
}
}
| 3,808 | 24.563758 | 118 | java |
Paddle-Lite-develop/lite/api/android/jni/src/com/baidu/paddle/lite/PowerMode.java | Paddle-Lite-develop/lite/api/android/jni/src/com/baidu/paddle/lite/PowerMode.java | /* Copyright (c) 2019 PaddlePaddle Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License. */
package com.baidu.paddle.lite;
/**
* PowerMode is the cpu running power mode for the light weight predictor.
*/
public enum PowerMode {
LITE_POWER_HIGH(0),
LITE_POWER_LOW(1),
LITE_POWER_FULL(2),
LITE_POWER_NO_BIND(3),
LITE_POWER_RAND_HIGH(4),
LITE_POWER_RAND_LOW(5);
private PowerMode(int value) {
this.value = value;
}
public int value() {
return this.value;
}
private final int value;
}
| 1,052 | 27.459459 | 74 | java |
Paddle-Lite-develop/lite/api/android/jni/src/com/baidu/paddle/lite/Tensor.java | Paddle-Lite-develop/lite/api/android/jni/src/com/baidu/paddle/lite/Tensor.java | /* Copyright (c) 2019 PaddlePaddle Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License. */
package com.baidu.paddle.lite;
/**
* Tensor class provides the Java APIs that users can get or set the shape or
* the data of a Tensor.
*/
public class Tensor {
/**
* Java doesn't have pointer. To maintain the life cycle of underneath C++
* Tensor object, we use a long value to maintain it.
*/
private long cppTensorPointer;
/**
* Is this tensor read-only. This field is also used at C++ side to know whether
* we should interpret the C++ tensor pointer to "Tensor" pointer or "const
* Tensor" pointer.
*/
private boolean readOnly;
/**
* Due to different memory management of Java and C++, at C++, if a user
* destroys PaddlePredictor object, the tensor's memory will be released and a
* pointer operating on the released tensor will cause unknown behavior. At C++
* side, that's users' responsibility to manage memory well. But for our Java
* code, we have to prevent this case. We make this {@link Tensor} keep a
* reference to {@link PaddlePredictor} to prevent the {@link PaddlePredictor}
* object be collected by JVM before {@Tensor}.
*/
private PaddlePredictor predictor;
/**
* Accessed by package only to prevent public users to create it wrongly. A
* Tensor can be created by {@link com.baidu.paddle.lite.PaddlePredictor} only
*/
protected Tensor(long cppTensorPointer, boolean readOnly, PaddlePredictor predictor) {
this.cppTensorPointer = cppTensorPointer;
this.readOnly = readOnly;
this.predictor = predictor;
}
/** Deletes C++ Tensor pointer when Java Tensor object is destroyed */
protected void finalize() throws Throwable {
if (cppTensorPointer != 0L) {
deleteCppTensor(cppTensorPointer);
cppTensorPointer = 0L;
}
super.finalize();
}
/**
* @return whether this Tensor is read-only.
*/
public boolean isReadOnly() {
return readOnly;
}
/**
* Resizes the tensor shape.
*
* @param dims long array of shape.
* @return true if resize successfully.
*/
public boolean resize(long[] dims) {
if (readOnly) {
return false;
}
return nativeResize(dims);
}
/**
* Set the tensor float data.
*
* @param buf the float array buffer which will be copied into tensor.
* @return true if set data successfully.
*/
public boolean setData(float[] buf) {
if (readOnly) {
return false;
}
return nativeSetData(buf);
}
/**
* Set the tensor byte data.
*
* @param buf the byte array buffer which will be copied into tensor.
* @return true if set data successfully.
*/
public boolean setData(byte[] buf) {
if (readOnly) {
return false;
}
return nativeSetData(buf);
}
/**
* Set the tensor int data.
*
* @param buf the int array buffer which will be copied into tensor.
* @return true if set data successfully.
*/
public boolean setData(int[] buf) {
if (readOnly) {
return false;
}
return nativeSetData(buf);
}
/**
* Set the tensor int data.
*
* @param buf the int array buffer which will be copied into tensor.
* @return true if set data successfully.
*/
public boolean setData(long[] buf) {
if (readOnly) {
return false;
}
return nativeSetData(buf);
}
/**
* @return shape of the tensor as long array.
*/
public native long[] shape();
/**
* @return the tensor data as float array.
*/
public native float[] getFloatData();
/**
* @return the tensor data as byte array.
*/
public native byte[] getByteData();
/**
* @return the tensor data as int array.
*/
public native int[] getIntData();
/**
* @return the tensor data as long array.
*/
public native long[] getLongData();
private native boolean nativeResize(long[] dims);
private native boolean nativeSetData(float[] buf);
private native boolean nativeSetData(byte[] buf);
private native boolean nativeSetData(int[] buf);
private native boolean nativeSetData(long[] buf);
/**
* Delete C++ Tenor object pointed by the input pointer, which is presented by a
* long value.
*
* @param nativePointer a long value which is reinterpret_cast of the C++
* pointer.
* @return true if deletion success.
*/
private native boolean deleteCppTensor(long nativePointer);
} | 5,288 | 28.220994 | 90 | java |
Paddle-Lite-develop/lite/api/android/jni/test/com/baidu/paddle/lite/PaddlePredictorTest.java | Paddle-Lite-develop/lite/api/android/jni/test/com/baidu/paddle/lite/PaddlePredictorTest.java | /* Copyright (c) 2019 PaddlePaddle Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License. */
package com.baidu.paddle.lite;
import org.junit.jupiter.api.Test;
import static org.junit.Assert.assertEquals;
/**
* Deprecated test. Now we use Android demo's Instrument test.
*
* @TODO make this test as Java Unit test. Then we don't have to launch Android
* demo to test.
*/
class PaddlePredictorTest {
@Test
public void run_defaultModel() {
MobileConfig config = new MobileConfig();
config.setModelDir("");
PaddlePredictor predictor = PaddlePredictor.createPaddlePredictor(config);
float[] inputBuffer = new float[10000];
for (int i = 0; i < 10000; ++i) {
inputBuffer[i] = i;
}
long[] dims = { 100, 100 };
Tensor input = predictor.getInput(0);
input.resize(dims);
input.setData(inputBuffer);
predictor.run();
Tensor output = predictor.getOutput(0);
float[] outputBuffer = output.getFloatData();
assertEquals(outputBuffer.length, 50000);
assertEquals(outputBuffer[0], 50.2132f, 1e-3f);
assertEquals(outputBuffer[1], -28.8729f, 1e-3f);
}
}
| 1,708 | 30.072727 | 82 | java |
Paddle-Lite-develop/lite/demo/java/android/PaddlePredictor/app/src/androidTest/java/com/baidu/paddle/lite/ExampleInstrumentedTest.java | Paddle-Lite-develop/lite/demo/java/android/PaddlePredictor/app/src/androidTest/java/com/baidu/paddle/lite/ExampleInstrumentedTest.java | package com.baidu.paddle.lite;
import android.content.Context;
import android.support.test.InstrumentationRegistry;
import android.support.test.runner.AndroidJUnit4;
import org.junit.Test;
import org.junit.runner.RunWith;
import java.util.ArrayList;
import static org.junit.Assert.*;
/**
* Lite example Instrument test
*/
@RunWith(AndroidJUnit4.class)
public class ExampleInstrumentedTest {
@Test
public void naiveModel_isCorrect() {
Context appContext = InstrumentationRegistry.getTargetContext();
ArrayList<Tensor> result = MainActivity.setInputAndRunNaiveModel("lite_naive_model", appContext);
Tensor output = result.get(0);
long[] shape = output.shape();
assertEquals(2, shape.length);
assertEquals(100L, shape[0]);
assertEquals(500L, shape[1]);
float[] outputBuffer = output.getFloatData();
assertEquals(50000, outputBuffer.length);
assertEquals(50.2132f, outputBuffer[0], 1e-4);
assertEquals(-28.8729, outputBuffer[1], 1e-4);
}
@Test
public void inceptionV4Simple_isCorrect() {
Context appContext = InstrumentationRegistry.getTargetContext();
ArrayList<Tensor> result = MainActivity.setInputAndRunImageModel("inception_v4_simple", appContext);
float[] expected = {0.0011684548f, 0.0010390386f, 0.0011301535f, 0.0010133048f,
0.0010259597f, 0.0010982729f, 0.00093195855f, 0.0009141837f,
0.00096620916f, 0.00089982944f, 0.0010064574f, 0.0010474789f,
0.0009782845f, 0.0009230255f, 0.0010548076f, 0.0010974824f,
0.0010612885f, 0.00089107914f, 0.0010112736f, 0.00097655767f};
assertImageResult(expected, result);
}
@Test
public void mobilenetV1_isCorrect() {
Context appContext = InstrumentationRegistry.getTargetContext();
ArrayList<Tensor> result = MainActivity.setInputAndRunImageModel("mobilenet_v1", appContext);
float[] expected = {0.00019130898f, 9.467885e-05f, 0.00015971427f, 0.0003650665f,
0.00026431272f, 0.00060884043f, 0.0002107942f, 0.0015819625f,
0.0010323516f, 0.00010079765f, 0.00011006987f, 0.0017364529f,
0.0048292773f, 0.0013995157f, 0.0018453331f, 0.0002428986f,
0.00020211363f, 0.00013668182f, 0.0005855956f, 0.00025901722f};
assertImageResult(expected, result);
}
@Test
public void mobilenetV2Relu_isCorrect() {
Context appContext = InstrumentationRegistry.getTargetContext();
ArrayList<Tensor> result = MainActivity.setInputAndRunImageModel("mobilenet_v2_relu", appContext);
float[] expected = {0.00017082224f, 5.699624e-05f, 0.000260885f, 0.00016412718f,
0.00034818667f, 0.00015230637f, 0.00032959113f, 0.0014772735f,
0.0009059976f, 9.5378724e-05f, 5.386537e-05f, 0.0006427285f,
0.0070957416f, 0.0016094646f, 0.0018807327f, 0.00010506048f,
6.823785e-05f, 0.00012269315f, 0.0007806194f, 0.00022354358f};
assertImageResult(expected, result);
}
@Test
public void resnet50_isCorrect() {
Context appContext = InstrumentationRegistry.getTargetContext();
ArrayList<Tensor> result = MainActivity.setInputAndRunImageModel("resnet50", appContext);
float[] expected = {0.00024139918f, 0.00020566184f, 0.00022418296f, 0.00041731037f,
0.0005366107f, 0.00016948722f, 0.00028638865f, 0.0009257241f,
0.00072681636f, 8.531815e-05f, 0.0002129998f, 0.0021168243f,
0.006387163f, 0.0037145028f, 0.0012812682f, 0.00045948103f,
0.00013535398f, 0.0002483765f, 0.00076759676f, 0.0002773295f};
assertImageResult(expected, result);
}
public void assertImageResult(float[] expected, ArrayList<Tensor> result) {
assertEquals(2, result.size());
assertEquals(20, expected.length);
Tensor tensor = result.get(0);
Tensor tensor1 = result.get(1);
long[] shape = tensor.shape();
long[] shape1 = tensor1.shape();
assertEquals(2, shape.length);
assertEquals(2, shape1.length);
assertEquals(1L, shape[0]);
assertEquals(1L, shape1[0]);
assertEquals(1000L, shape[1]);
assertEquals(1000L, shape1[1]);
float[] output = tensor.getFloatData();
float[] output1 = tensor.getFloatData();
assertEquals(1000, output.length);
assertEquals(1000, output1.length);
for (int i = 0; i < output.length; ++i) {
assertEquals(output[i], output1[i], 1e-6f);
}
int step = 50;
for (int i = 0; i < expected.length; ++i) {
assertEquals(output[i * step], expected[i], 1e-6f);
}
}
}
| 4,793 | 40.686957 | 108 | java |
Paddle-Lite-develop/lite/demo/java/android/PaddlePredictor/app/src/main/java/com/baidu/paddle/lite/MainActivity.java | Paddle-Lite-develop/lite/demo/java/android/PaddlePredictor/app/src/main/java/com/baidu/paddle/lite/MainActivity.java | package com.baidu.paddle.lite;
import android.content.Context;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.TextView;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Date;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
String textOutput = "";
String version = getVersionInfo("lite_naive_model_opt.nb", this);
textOutput += "Version: " + version + "\n";
Tensor output;
output = setInputAndRunNaiveModel("lite_naive_model_opt.nb", this);
textOutput += "\nlite_naive_model output: " + output.getFloatData()[0] + ", "
+ output.getFloatData()[1] + "\n";
textOutput += "expected: 50.2132, -28.8729\n";
Date start = new Date();
output = setInputAndRunImageModel("inception_v4_simple_opt.nb", this);
Date end = new Date();
textOutput += "\ninception_v4_simple test: " + testInceptionV4Simple(output) + "\n";
textOutput += "time: " + (end.getTime() - start.getTime()) + " ms\n";
start = new Date();
output = setInputAndRunImageModel("resnet50_opt.nb", this);
end = new Date();
textOutput += "\nresnet50 test: " + testResnet50(output) + "\n";
textOutput += "time: " + (end.getTime() - start.getTime()) + " ms\n";
start = new Date();
output = setInputAndRunImageModel("mobilenet_v1_opt.nb", this);
end = new Date();
textOutput += "\nmobilenet_v1 test: " + testMobileNetV1(output) + "\n";
textOutput += "time: " + (end.getTime() - start.getTime()) + " ms\n";
start = new Date();
output = setInputAndRunImageModel("mobilenet_v2_relu_opt.nb", this);
end = new Date();
textOutput += "\nmobilenet_v2 test: " + testMobileNetV2Relu(output) + "\n";
textOutput += "time: " + (end.getTime() - start.getTime()) + " ms\n";
TextView textView = findViewById(R.id.text_view);
textView.setText(textOutput);
}
public static String getVersionInfo(String modelName, Context context) {
String modelPath = copyFromAssetsToCache(modelName, context);
MobileConfig config = new MobileConfig();
config.setModelFromFile(modelPath);
PaddlePredictor predictor = PaddlePredictor.createPaddlePredictor(config);
return predictor.getVersion();
}
public static String copyFromAssetsToCache(String modelPath, Context context) {
String newPath = context.getCacheDir() + "/" + modelPath;
File desDir = new File(newPath);
try {
InputStream stream = context.getAssets().open(modelPath);
OutputStream output = new BufferedOutputStream(new FileOutputStream(newPath));
byte data[] = new byte[1024];
int count;
while ((count = stream.read(data)) != -1) {
output.write(data, 0, count);
}
output.flush();
output.close();
stream.close();
} catch (Exception e) {
throw new RuntimeException(e);
}
return desDir.getPath();
}
public static Tensor runModel(String modelName, long[] dims, float[] inputBuffer, Context context) {
String modelPath = copyFromAssetsToCache(modelName, context);
MobileConfig config = new MobileConfig();
config.setModelFromFile(modelPath);
config.setPowerMode(PowerMode.LITE_POWER_HIGH);
config.setThreads(1);
PaddlePredictor predictor = PaddlePredictor.createPaddlePredictor(config);
Tensor input = predictor.getInput(0);
input.resize(dims);
input.setData(inputBuffer);
predictor.run();
Tensor output = predictor.getOutput(0);
return output;
}
public static Tensor setInputAndRunNaiveModel(String modelName, Context context) {
long[] dims = {100, 100};
float[] inputBuffer = new float[10000];
for (int i = 0; i < 10000; ++i) {
inputBuffer[i] = i;
}
return runModel(modelName, dims, inputBuffer, context);
}
/**
* Input size is 3 * 224 * 224
*
* @param modelName
* @return
*/
public static Tensor setInputAndRunImageModel(String modelName, Context context) {
long[] dims = {1, 3, 224, 224};
int item_size = 3 * 224 * 224;
float[] inputBuffer = new float[item_size];
for (int i = 0; i < item_size; ++i) {
inputBuffer[i] = 1;
}
return runModel(modelName, dims, inputBuffer, context);
}
public boolean equalsNear(float a, float b, float delta) {
return a >= b - delta && a <= b + delta;
}
public boolean expectedResult(float[] expected, Tensor result) {
if (expected.length != 20) {
return false;
}
long[] shape = result.shape();
if (shape.length != 2) {
return false;
}
if (shape[0] != 1 || shape[1] != 1000) {
return false;
}
float[] output = result.getFloatData();
if (output.length != 1000) {
return false;
}
int step = 50;
for (int i = 0; i < expected.length; ++i) {
if (!equalsNear(output[i * step], expected[i], 1e-6f)) {
return false;
}
}
return true;
}
public boolean testInceptionV4Simple(Tensor output) {
float[] expected = {0.0011684548f, 0.0010390386f, 0.0011301535f, 0.0010133048f,
0.0010259597f, 0.0010982729f, 0.00093195855f, 0.0009141837f,
0.00096620916f, 0.00089982944f, 0.0010064574f, 0.0010474789f,
0.0009782845f, 0.0009230255f, 0.0010548076f, 0.0010974824f,
0.0010612885f, 0.00089107914f, 0.0010112736f, 0.00097655767f};
return expectedResult(expected, output);
}
public boolean testResnet50(Tensor output) {
float[] expected = {0.00024139918f, 0.00020566184f, 0.00022418296f, 0.00041731037f,
0.0005366107f, 0.00016948722f, 0.00028638865f, 0.0009257241f,
0.00072681636f, 8.531815e-05f, 0.0002129998f, 0.0021168243f,
0.006387163f, 0.0037145028f, 0.0012812682f, 0.00045948103f,
0.00013535398f, 0.0002483765f, 0.00076759676f, 0.0002773295f};
return expectedResult(expected, output);
}
public boolean testMobileNetV1(Tensor output) {
float[] expected = {0.00019130898f, 9.467885e-05f, 0.00015971427f, 0.0003650665f,
0.00026431272f, 0.00060884043f, 0.0002107942f, 0.0015819625f,
0.0010323516f, 0.00010079765f, 0.00011006987f, 0.0017364529f,
0.0048292773f, 0.0013995157f, 0.0018453331f, 0.0002428986f,
0.00020211363f, 0.00013668182f, 0.0005855956f, 0.00025901722f};
return expectedResult(expected, output);
}
public boolean testMobileNetV2Relu(Tensor output) {
float[] expected = {0.00017082224f, 5.699624e-05f, 0.000260885f, 0.00016412718f,
0.00034818667f, 0.00015230637f, 0.00032959113f, 0.0014772735f,
0.0009059976f, 9.5378724e-05f, 5.386537e-05f, 0.0006427285f,
0.0070957416f, 0.0016094646f, 0.0018807327f, 0.00010506048f,
6.823785e-05f, 0.00012269315f, 0.0007806194f, 0.00022354358f};
return expectedResult(expected, output);
}
}
| 7,764 | 35.627358 | 104 | java |
Paddle-Lite-develop/lite/demo/java/android/PaddlePredictor/app/src/test/java/com/baidu/paddle/lite/ExampleUnitTest.java | Paddle-Lite-develop/lite/demo/java/android/PaddlePredictor/app/src/test/java/com/baidu/paddle/lite/ExampleUnitTest.java | package com.baidu.paddle.lite;
import org.junit.Test;
import static org.junit.Assert.*;
/**
* Example local unit test, which will execute on the development machine (host).
*
* @see <a href="http://d.android.com/tools/testing">Testing documentation</a>
*/
public class ExampleUnitTest {
@Test
public void addition_isCorrect() {
assertEquals(4, 2 + 2);
}
} | 382 | 21.529412 | 81 | java |
AMLSim | AMLSim-master/src/main/java/amlsim/AMLSim.java | package amlsim;
import amlsim.model.AbstractTransactionModel;
import amlsim.model.ModelParameters;
import amlsim.model.cash.CashInModel;
import amlsim.model.cash.CashOutModel;
import amlsim.model.normal.EmptyModel;
import amlsim.model.normal.FanInTransactionModel;
import amlsim.model.normal.FanOutTransactionModel;
import amlsim.model.normal.ForwardTransactionModel;
import amlsim.model.normal.MutualTransactionModel;
import amlsim.model.normal.PeriodicalTransactionModel;
import amlsim.model.normal.SingleTransactionModel;
import amlsim.model.aml.AMLTypology;
import amlsim.stat.Diameter;
import sim.engine.SimState;
import java.io.*;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.logging.*;
/**
* AMLSimulator Main class
*/
public class AMLSim extends SimState {
private static SimProperties simProp;
private static final int TX_SIZE = 10000000; // Transaction buffer size
private static TransactionRepository txs = new TransactionRepository(TX_SIZE);
private static Logger logger = Logger.getLogger("AMLSim");
// private static int seed;
private static Random rand;
private Map<String, Integer> idMap = new HashMap<>(); // Account ID --> Index
private Map<Long, Alert> alerts = new HashMap<>(); // Alert ID --> Alert (AML typology) object
private Map<Long, AccountGroup> accountGroupsMap = new HashMap<>();
private int numBranches = 0;
private ArrayList<Branch> branches = new ArrayList<>();
private int normalTxInterval = 30; // Default transaction interval for normal accounts
// private int sarTxInterval = 10; // Default transaction interval for SAR accounts
// private float sarBalanceRatio = 10.0F; // Multiplier of initial balance for SAR accounts
private static String simulatorName = null;
private ArrayList<String> paramFile = new ArrayList<>();
private ArrayList<String> actions = new ArrayList<>();
private ArrayList<Account> accounts = new ArrayList<Account>();
private BufferedWriter bufWriter;
private static long numOfSteps = 1; // Number of simulation steps
private static int currentLoop = 0; // Simulation iteration counter
private static String txLogFileName = "";
private String accountFile = "";
private String transactionFile = "";
private String normalModelsFile = "";
private String alertMemberFile = "";
private String counterFile = "";
private String diameterFile = "";
private static Diameter diameter;
private boolean computeDiameter = false;
private AMLSim(long seed) {
super(seed);
AMLSim.rand = new Random(seed);
Handler handler = new ConsoleHandler();
logger.addHandler(handler);
java.util.logging.Formatter formatter = new SimpleFormatter();
handler.setFormatter(formatter);
simulatorName = simProp.getSimName();
}
public static Random getRandom(){
return rand;
}
public static Logger getLogger(){
return logger;
}
public static SimProperties getSimProp(){
return simProp;
}
public void setCurrentLoop(int currentLoop){
AMLSim.currentLoop = currentLoop;
}
private List<Account> getAccounts() {
return this.accounts;
}
/**
* Get the number of simulation steps
* @return Simulation steps as long
*/
public static long getNumOfSteps(){
return numOfSteps;
}
/**
* Get an account object from an account ID
* @param id Account ID
* @return Account object
*/
private Account getAccountFromID(String id){
int index = this.idMap.get(id);
return (Account) this.getAccounts().get(index);
}
/**
* Initialize AMLSim by loading account and transaction list files
*/
public void initSimulation() {
try {
loadAccountFile(this.accountFile);
} catch (IOException e) {
System.err.println("Cannot load account file: " + this.accountFile);
e.printStackTrace();
System.exit(1);
}
try {
loadTransactionFile(this.transactionFile);
} catch (IOException e) {
System.err.println("Cannot load transaction file: " + this.transactionFile);
e.printStackTrace();
System.exit(1);
}
try {
loadNormalModelsFile(this.normalModelsFile);
} catch (IOException e) {
System.err.println("Cannot load normal model file: " + this.normalModelsFile);
e.printStackTrace();
System.exit(1);
}
try {
loadAlertMemberFile(this.alertMemberFile);
} catch (IOException e) {
System.err.println("Cannot load alert file: " + this.alertMemberFile);
e.printStackTrace();
System.exit(1);
}
}
public void loadParametersFromFile() {
numOfSteps = simProp.getSteps();
// Default transaction interval for accounts
this.normalTxInterval = simProp.getNormalTransactionInterval();
// Number of transactions for logging buffer
int transactionLimit = simProp.getTransactionLimit();
if(transactionLimit > 0){ // Set the limit only if the parameter is positive value
txs.setLimit(transactionLimit);
}
// Parameters of Cash Transactions
int norm_in_int = simProp.getCashTxInterval(true, false); // Interval of cash-in transactions for normal account
int suspicious_in_int = simProp.getCashTxInterval(true, true); // Interval of cash-in transactions for suspicious account
float norm_in_min = simProp.getCashTxMinAmount(true, false); // Minimum amount of cash-in transactions for normal account
float norm_in_max = simProp.getCashTxMaxAmount(true, false); // Maximum amount of cash-in transactions for normal account
float suspicious_in_min = simProp.getCashTxMinAmount(true, true); // Minimum amount of cash-in transactions for suspicious account
float suspicious_in_max = simProp.getCashTxMaxAmount(true, true); // Maximum amount of cash-in transactions for suspicious account
CashInModel.setParam(norm_in_int, suspicious_in_int, norm_in_min, norm_in_max, suspicious_in_min, suspicious_in_max);
int norm_out_int = simProp.getCashTxInterval(false, false); // Interval of cash-out transactions for normal account
int suspicious_out_int = simProp.getCashTxInterval(false, true); // Interval of cash-out transactions for suspicious account
float norm_out_min = simProp.getCashTxMinAmount(false, false); // Minimum amount of cash-out transactions for normal account
float norm_out_max = simProp.getCashTxMaxAmount(false, false); // Maximum amount of cash-out transactions for normal account
float suspicious_out_min = simProp.getCashTxMinAmount(false, true); // Minimum amount of cash-out transactions for suspicious account
float suspicious_out_max = simProp.getCashTxMaxAmount(false, true); // Maximum amount of cash-out transactions for suspicious account
CashOutModel.setParam(norm_out_int, suspicious_out_int, norm_out_min, norm_out_max, suspicious_out_min, suspicious_out_max);
// Create branches (for cash transactions)
this.numBranches = simProp.getNumBranches();
if(this.numBranches <= 0){
throw new IllegalStateException("The numBranches must be positive");
}
for(int i=0; i<this.numBranches; i++) {
this.branches.add(new Branch(i));
}
this.accountFile = simProp.getInputAcctFile();
this.transactionFile = simProp.getInputTxFile();
this.normalModelsFile = simProp.getNormalModelsFile();
this.alertMemberFile = simProp.getInputAlertMemberFile();
this.counterFile = simProp.getCounterLogFile();
this.diameterFile = simProp.getDiameterLogFile();
this.computeDiameter = simProp.isComputeDiameter();
if(computeDiameter && diameterFile != null){
try{
BufferedWriter writer = new BufferedWriter(new FileWriter(diameterFile));
writer.close();
}catch (IOException e){
e.printStackTrace();
computeDiameter = false;
}
if(computeDiameter){
logger.info("Compute transaction graph diameters and write them to: " + diameterFile);
}else{
logger.info("Transaction graph diameter computation is disabled");
}
}
}
private static Map<String, Integer> getColumnIndices(String header){
Map<String, Integer> columnIndex = new HashMap<>();
String[] element= header.split(",");
for(int i=0; i<element.length; i++){
columnIndex.put(element[i], i);
}
return columnIndex;
}
private void loadAccountFile(String accountFile) throws IOException{
BufferedReader reader = new BufferedReader(new FileReader(accountFile));
String line = reader.readLine();
logger.info("Account CSV header: " + line);
Map<String, Integer> columnIndex = getColumnIndices(line);
while((line = reader.readLine()) != null){
String[] elements = line.split(",");
String accountID = elements[columnIndex.get("ACCOUNT_ID")];
boolean isSAR = elements[columnIndex.get("IS_SAR")].toLowerCase().equals("true");
float initBalance = Float.parseFloat(elements[columnIndex.get("INIT_BALANCE")]);
String bankID = elements[columnIndex.get("BANK_ID")];
Account account;
if (isSAR) {
account = new SARAccount(accountID, normalTxInterval, initBalance, bankID,
getRandom());
} else {
account = new Account(accountID, normalTxInterval, initBalance, bankID,
getRandom());
}
int index = this.getAccounts().size();
account.setBranch(this.branches.get(index % this.numBranches));
this.getAccounts().add(account);
this.idMap.put(accountID, index);
this.schedule.scheduleRepeating(account);
}
int numAccounts = idMap.size();
logger.info("Number of total accounts: " + numAccounts);
diameter = new Diameter(numAccounts);
reader.close();
}
private void loadTransactionFile(String transactionFile) throws IOException{
BufferedReader reader = new BufferedReader(new FileReader(transactionFile));
String line = reader.readLine();
Map<String, Integer> columnIndex = getColumnIndices(line);
while((line = reader.readLine()) != null){
String[] elements = line.split(",");
String srcID = elements[columnIndex.get("src")];
String dstID = elements[columnIndex.get("dst")];
String ttype = elements[columnIndex.get("ttype")];
Account src = getAccountFromID(srcID);
Account dst = getAccountFromID(dstID);
src.addBeneAcct(dst);
src.addTxType(dst, ttype);
}
reader.close();
}
private void loadNormalModelsFile(String filename) throws IOException {
try (BufferedReader reader = new BufferedReader(new FileReader(filename))) {
String line;
line = reader.readLine();
Map<String, Integer> columnIndexMap = getColumnIndices(line);
while((line = reader.readLine()) != null) {
String[] elements = line.split(",");
String type = elements[columnIndexMap.get("type")];
String accountID = elements[columnIndexMap.get("accountID")];
long accountGroupId = Long.parseLong(elements[columnIndexMap.get("modelID")]);
boolean isMain = elements[columnIndexMap.get("isMain")].toLowerCase().equals("true");
AccountGroup accountGroup;
if (this.accountGroupsMap.containsKey(accountGroupId)) {
accountGroup = this.accountGroupsMap.get(accountGroupId);
}
else {
accountGroup = new AccountGroup(accountGroupId, this);
accountGroupsMap.put(accountGroupId, accountGroup);
}
Account account = getAccountFromID(accountID);
accountGroup.addMember(account);
if (isMain) {
accountGroup.setMainAccount(account);
}
account.addAccountGroup(accountGroup);
AbstractTransactionModel model;
switch (type) {
case AbstractTransactionModel.SINGLE: model = new SingleTransactionModel(accountGroup, rand); break;
case AbstractTransactionModel.FAN_OUT: model= new FanOutTransactionModel(accountGroup, rand); break;
case AbstractTransactionModel.FAN_IN: model = new FanInTransactionModel(accountGroup, rand); break;
case AbstractTransactionModel.MUTUAL: model = new MutualTransactionModel(accountGroup, rand); break;
case AbstractTransactionModel.FORWARD: model = new ForwardTransactionModel(accountGroup, rand); break;
case AbstractTransactionModel.PERIODICAL: model = new PeriodicalTransactionModel(accountGroup, rand); break;
default: System.err.println("Unknown model type: " + type); model = new EmptyModel(accountGroup, rand); break;
}
accountGroup.setModel(model);
model.setParameters(this.normalTxInterval, -1, -1);
}
}
}
private void loadAlertMemberFile(String alertFile) throws IOException{
logger.info("Load alert member list from:" + alertFile);
BufferedReader reader = new BufferedReader(new FileReader(alertFile));
String line = reader.readLine();
Map<String, Integer> columnIndex = getColumnIndices(line);
Map<Long, Integer> scheduleModels = new HashMap<>();
while((line = reader.readLine()) != null){
String[] elements = line.split(",");
long alertID = Long.parseLong(elements[columnIndex.get("alertID")]);
String accountID = elements[columnIndex.get("accountID")];
boolean isMain = elements[columnIndex.get("isMain")].toLowerCase().equals("true");
boolean isSAR = elements[columnIndex.get("isSAR")].toLowerCase().equals("true");
int modelID = Integer.parseInt(elements[columnIndex.get("modelID")]);
double minAmount = Double.parseDouble(elements[columnIndex.get("minAmount")]);
double maxAmount = Double.parseDouble(elements[columnIndex.get("maxAmount")]);
int startStep = Integer.parseInt(elements[columnIndex.get("startStep")]);
int endStep = Integer.parseInt(elements[columnIndex.get("endStep")]);
int scheduleID = Integer.parseInt(elements[columnIndex.get("scheduleID")]);
if(minAmount > maxAmount){
throw new IllegalArgumentException(String.format("minAmount %f is larger than maxAmount %f", minAmount, maxAmount));
}
if(startStep > endStep){
throw new IllegalArgumentException(String.format("startStep %d is larger than endStep %d", startStep, endStep));
}
Alert alert;
if(alerts.containsKey(alertID)){ // Get an AML typology object and update the minimum/maximum amount
alert = alerts.get(alertID);
AMLTypology model = alert.getModel();
model.updateMinAmount(minAmount);
model.updateMaxAmount(maxAmount);
model.updateStartStep(startStep);
model.updateEndStep(endStep);
}else{ // Create a new AML typology object
AMLTypology model = AMLTypology.createTypology(modelID, minAmount, maxAmount, startStep, endStep);
alert = new Alert(alertID, model, this);
alerts.put(alertID, alert);
}
Account account = getAccountFromID(accountID);
alert.addMember(account);
if(isMain){
alert.setMainAccount(account);
}
account.setSAR(isSAR);
scheduleModels.put(alertID, scheduleID);
}
for(long alertID : scheduleModels.keySet()){
int modelID = scheduleModels.get(alertID);
alerts.get(alertID).getModel().setParameters(modelID);
}
reader.close();
}
/**
* Define the simulator name and an output log directory.
* If the simulator name is not specified, generate it using the current time.
*/
private void initSimulatorName() {
if(AMLSim.simulatorName == null) { // Not specified in the args
Calendar c = Calendar.getInstance();
SimpleDateFormat format = new SimpleDateFormat("yyyyMMdd_HHmmss_SSS");
AMLSim.simulatorName = "PS_" + format.format(c.getTime());
}
logger.info("Simulator Name: " + AMLSim.simulatorName);
String dirPath = simProp.getOutputDir();
File f = new File(dirPath);
if(f.exists()){
logger.warning("Output log directory already exists: " + dirPath);
}else {
boolean result = f.mkdir();
if (!result) {
throw new IllegalStateException("Output log directory cannot be created to: " + dirPath);
}
}
}
private void initTxLogBufWriter(String logFileName) {
try {
FileWriter writer = new FileWriter(new File(logFileName));
this.bufWriter = new BufferedWriter(writer);
this.bufWriter.write("step,type,amount,nameOrig,oldbalanceOrig,newbalanceOrig,nameDest,oldbalanceDest,newbalanceDest,isSAR,alertID\n");
this.bufWriter.close();
} catch (IOException e) {
e.printStackTrace();
}
}
static String getTxLogFileName(){
return txLogFileName;
}
public void executeSimulation(){
//Load the parameters from the .property file
loadParametersFromFile();
// increase transfer limit with the current loop
initSimulatorName();
//Initiate the dumpfile output writer
txLogFileName = simProp.getOutputTxLogFile();
initTxLogBufWriter(txLogFileName);
logger.info("Transaction log file: " + txLogFileName);
// Create account objects
super.start();
this.initSimulation();
// Starting the simulation
long begin = System.currentTimeMillis();
System.out.println("Starting AMLSim Running for " + numOfSteps + " steps. Current loop:" + AMLSim.currentLoop);
long step;
while ((step = super.schedule.getSteps()) < numOfSteps) {
if (!super.schedule.step(this))
break;
if (step % 100 == 0 && step != 0) {
long tm = System.currentTimeMillis();
System.out.println("Time Step " + step + ", " + (tm - begin)/1000 + " [s]");
}
else {
System.out.print("*");
}
if (computeDiameter && step % 10 == 0 && step > 0){
double[] result = diameter.computeDiameter();
writeDiameter(step, result);
}
}
txs.flushLog();
txs.writeCounterLog(numOfSteps, counterFile);
System.out.println(" - Finished running " + step + " steps ");
//Finishing the simulation
super.finish();
long end = System.currentTimeMillis();
double total = end - begin;
total = total/1000; // ms --> s
System.out.println("\nIt took: " + total + " seconds to execute the simulation\n");
System.out.println("Simulation name: " + AMLSim.simulatorName);
}
/**
* Manage a transaction for logging and diameter computation of the whole transaction network
* @param step Simulation step
* @param desc Transaction description (e.g. type)
* @param amt Amount
* @param orig Originator account
* @param bene Beneficiary account
* @param isSAR SAR flag
* @param alertID Alert ID
*/
public static void handleTransaction(long step, String desc, double amt, Account orig, Account bene,
boolean isSAR, long alertID){
// Reduce the balance of the originator account
String origID = orig.getID();
float origBefore = (float)orig.getBalance();
orig.withdraw(amt);
float origAfter = (float)orig.getBalance();
// Increase the balance of the beneficiary account
String beneID = bene.getID();
float beneBefore = (float)bene.getBalance();
bene.deposit(amt);
float beneAfter = (float)bene.getBalance();
txs.addTransaction(step, desc, amt, origID, beneID, origBefore, origAfter, beneBefore, beneAfter, isSAR, alertID);
diameter.addEdge(origID, beneID);
}
/**
* Write diameters of the transaction network snapshots to a CSV file
* @param step Simulation step
* @param result Diameter and radius of the transaction network as double array
*/
private void writeDiameter(long step, double[] result){
try{
BufferedWriter writer = new BufferedWriter(new FileWriter(diameterFile, true));
writer.write(step + "," + result[0] + "," + result[1] + "\n");
writer.close();
}catch (IOException e){
e.printStackTrace();
}
}
public static void main(String[] args){
if(args.length < 1){
System.err.println("Usage: java amlsim.AMLSim [ConfFile]");
System.exit(1);
}
// Loading configuration JSON file instead of parsing command line arguments
String confFile = args[0];
try {
simProp = new SimProperties(confFile);
}catch (IOException e){
System.err.println("Cannot load configuration JSON file: " + confFile);
e.printStackTrace();
System.exit(1);
}
if(args.length >= 2){ // Load transaction model parameter file (optional)
String propFile = args[1];
ModelParameters.loadProperties(propFile);
}
int seed = simProp.getSeed();
AMLSim sim = new AMLSim(seed);
sim.setCurrentLoop(0);
sim.executeSimulation();
}
}
| 20,226 | 35.910584 | 138 | java |
AMLSim | AMLSim-master/src/main/java/amlsim/Account.java | package amlsim;
import amlsim.model.*;
import amlsim.model.cash.CashInModel;
import amlsim.model.cash.CashOutModel;
import sim.engine.SimState;
import sim.engine.Steppable;
import java.util.*;
public class Account implements Steppable {
protected String id;
protected CashInModel cashInModel;
protected CashOutModel cashOutModel;
protected boolean isSAR = false;
private Branch branch = null;
private Set<String> origAcctIDs = new HashSet<>(); // Originator account ID set
private Set<String> beneAcctIDs = new HashSet<>(); // Beneficiary account ID set
private List<Account> origAccts = new ArrayList<>(); // Originator accounts from which this account receives money
private List<Account> beneAccts = new ArrayList<>(); // Beneficiary accounts to which this account sends money
private int numSARBene = 0; // Number of SAR beneficiary accounts
private String bankID = ""; // Bank ID
private Account prevOrig = null; // Previous originator account
List<Alert> alerts = new ArrayList<>();
List<AccountGroup> accountGroups = new ArrayList<>();
private Map<String, String> tx_types = new HashMap<>(); // Receiver Client ID --> Transaction Type
private static List<String> all_tx_types = new ArrayList<>();
private ArrayList<String> paramFile = new ArrayList<>();
private double balance = 0;
protected long startStep = 0;
protected long endStep = 0;
private Random random;
public Account() {
this.id = "-";
}
/**
* Constructor of the account object
* @param id Account ID
* @param interval Default transaction interval
* @param initBalance Initial account balance
* @param start Start step
* @param end End step
*/
public Account(String id, int interval, float initBalance, String bankID, Random rand) {
this.id = id;
this.setBalance(initBalance);
this.bankID = bankID;
this.random = rand;
this.cashInModel = new CashInModel();
this.cashInModel.setAccount(this);
this.cashInModel.setParameters(interval, -1, -1);
this.cashOutModel = new CashOutModel();
this.cashOutModel.setAccount(this);
this.cashOutModel.setParameters(interval, -1, -1);
}
public String getBankID() {
return this.bankID;
}
public long getStartStep(){
return this.startStep;
}
public long getEndStep(){
return this.endStep;
}
void setSAR(boolean flag){
this.isSAR = flag;
}
public boolean isSAR() {
return this.isSAR;
}
public double getBalance() {
return this.balance;
}
public void setBalance(double balance) {
this.balance = balance;
}
public void withdraw(double ammount) {
if (this.balance < ammount) {
this.balance = 0;
} else {
this.balance -= ammount;
}
}
public void deposit(double ammount){
this.balance += ammount;
}
void setBranch(Branch branch) {
this.branch = branch;
}
public Branch getBranch(){
return this.branch;
}
public void addBeneAcct(Account bene){
String beneID = bene.id;
if(beneAcctIDs.contains(beneID)){ // Already added
return;
}
if(ModelParameters.shouldAddEdge(this, bene)){
beneAccts.add(bene);
beneAcctIDs.add(beneID);
bene.origAccts.add(this);
bene.origAcctIDs.add(id);
if(bene.isSAR){
numSARBene++;
}
}
}
public void addTxType(Account bene, String ttype){
this.tx_types.put(bene.id, ttype);
all_tx_types.add(ttype);
}
public String getTxType(Account bene) {
String destID = bene.id;
if (this.tx_types.containsKey(destID)) {
return tx_types.get(destID);
} else if (!this.tx_types.isEmpty()) {
List<String> values = new ArrayList<>(this.tx_types.values());
return values.get(this.random.nextInt(values.size()));
} else {
return Account.all_tx_types.get(this.random.nextInt(Account.all_tx_types.size()));
}
}
/**
* Get previous (originator) accounts
* @return Originator account list
*/
public List<Account> getOrigList(){
return this.origAccts;
}
/**
* Get next (beneficiary) accounts
* @return Beneficiary account list
*/
public List<Account> getBeneList(){
return this.beneAccts;
}
public void printBeneList(){
System.out.println(this.beneAccts);
}
public int getNumSARBene(){
return this.numSARBene;
}
public float getPropSARBene(){
if(numSARBene == 0){
return 0.0F;
}
return (float)numSARBene / beneAccts.size();
}
/**
* Register this account to the specified alert.
* @param alert Alert
*/
public void addAlert(Alert alert) {
this.alerts.add(alert);
}
public void addAccountGroup(AccountGroup accountGroup) {
this.accountGroups.add(accountGroup);
}
/**
* Perform transactions
* @param state AMLSim object
*/
@Override
public void step(SimState state) {
long currentStep = state.schedule.getSteps(); // Current simulation step
long start = this.startStep >= 0 ? this.startStep : 0;
long end = this.endStep > 0 ? this.endStep : AMLSim.getNumOfSteps();
if(currentStep < start || end < currentStep){
return; // Skip transactions if this account is not active
}
handleAction(state);
}
public void handleAction(SimState state) {
AMLSim amlsim = (AMLSim) state;
long step = state.schedule.getSteps();
for (Alert alert : this.alerts) {
if (this == alert.getMainAccount()) {
alert.registerTransactions(step, this);
}
}
for (AccountGroup accountGroup : this.accountGroups) {
Account account = accountGroup.getMainAccount();
if (this == accountGroup.getMainAccount()) {
accountGroup.registerTransactions(step, account);
}
}
handleCashTransaction(amlsim);
}
/**
* Make cash transactions (deposit and withdrawal)
*/
private void handleCashTransaction(AMLSim amlsim){
long step = amlsim.schedule.getSteps();
this.cashInModel.makeTransaction(step);
this.cashOutModel.makeTransaction(step);
}
/**
* Get the previous originator account
* @return Previous originator account objects
*/
public Account getPrevOrig(){
return prevOrig;
}
public String getName() {
return this.id;
}
/**
* Get the account identifier as long
* @return Account identifier
*/
public String getID(){
return this.id;
}
/**
* Get the account identifier as String
* @return Account identifier
*/
public String toString() {
return "C" + this.id;
}
public ArrayList<String> getParamFile() {
return paramFile;
}
public void setParamFile(ArrayList<String> paramFile) {
this.paramFile = paramFile;
}
}
| 6,483 | 22.157143 | 119 | java |
AMLSim | AMLSim-master/src/main/java/amlsim/AccountGroup.java | package amlsim;
import amlsim.model.AbstractTransactionModel;
import java.util.*;
public class AccountGroup {
private long accountGroupId;
private List<Account> members; // Accounts involved in this alert
private Account mainAccount; // Main account of this alert
private AbstractTransactionModel model; // Transaction model
private AMLSim amlsim; // AMLSim main object
AccountGroup(long accountGroupId, AMLSim sim) {
this.accountGroupId = accountGroupId;
this.members = new ArrayList<>();
this.mainAccount = null;
this.amlsim = sim;
}
void setModel(AbstractTransactionModel model) {
this.model = model;
}
/**
* Add transactions
*
* @param step Current simulation step
*/
void registerTransactions(long step, Account acct) {
// maybe add is valid step.
model.sendTransactions(step, acct);
}
/**
* Involve an account in this alert
*
* @param acct Account object
*/
void addMember(Account acct) {
this.members.add(acct);
}
/**
* Get main AMLSim object
* @return AMLSim object
*/
public AMLSim getSimulator(){
return amlsim;
}
/**
* Get account group identifier as long type
* @return Account group identifier
*/
public long getAccoutGroupId(){
return this.accountGroupId;
}
/**
* Get member list of the alert
* @return Alert account list
*/
public List<Account> getMembers(){
return members;
}
/**
* Get the main account
* @return The main account if exists.
*/
public Account getMainAccount(){
return mainAccount;
}
/**
* Set the main account
* @param account Main account object
*/
void setMainAccount(Account account){
this.mainAccount = account;
}
public AbstractTransactionModel getModel() {
return model;
}
public boolean isSAR() {
return this.mainAccount != null && this.mainAccount.isSAR();
}
}
| 2,101 | 21.361702 | 70 | java |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.