repo stringlengths 1 191 ⌀ | file stringlengths 23 351 | code stringlengths 0 5.32M | file_length int64 0 5.32M | avg_line_length float64 0 2.9k | max_line_length int64 0 288k | extension_type stringclasses 1 value |
|---|---|---|---|---|---|---|
jmh | jmh-master/jmh-core/src/main/java/org/openjdk/jmh/runner/format/AbstractOutputFormat.java | /*
* Copyright (c) 2005, 2013, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package org.openjdk.jmh.runner.format;
import org.openjdk.jmh.runner.options.VerboseMode;
import java.io.IOException;
import java.io.PrintStream;
abstract class AbstractOutputFormat implements OutputFormat {
/** Verbose-mode? */
final VerboseMode verbose;
/** PrintStream to use */
final PrintStream out;
public AbstractOutputFormat(PrintStream out, VerboseMode verbose) {
this.out = out;
this.verbose = verbose;
}
@Override
public void print(String s) {
out.print(s);
}
@Override
public void println(String s) {
out.println(s);
}
@Override
public void flush() {
out.flush();
}
@Override
public void verbosePrintln(String s) {
if (verbose == VerboseMode.EXTRA) {
out.println(s);
}
}
@Override
public void write(int b) {
out.write(b);
}
@Override
public void write(byte[] b) throws IOException {
out.write(b);
}
@Override
public void close() {
// do nothing
}
}
| 2,287 | 26.902439 | 79 | java |
jmh | jmh-master/jmh-core/src/main/java/org/openjdk/jmh/runner/format/OutputFormat.java | /*
* Copyright (c) 2005, 2013, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package org.openjdk.jmh.runner.format;
import org.openjdk.jmh.infra.BenchmarkParams;
import org.openjdk.jmh.infra.IterationParams;
import org.openjdk.jmh.results.BenchmarkResult;
import org.openjdk.jmh.results.IterationResult;
import org.openjdk.jmh.results.RunResult;
import java.io.IOException;
import java.util.Collection;
/**
* Internal interface for OutputFormat.
*/
public interface OutputFormat {
/**
* Format for iteration start.
*
* @param benchParams benchmark parameters
* @param params iteration params in use
* @param iteration iteration-number
*/
void iteration(BenchmarkParams benchParams, IterationParams params, int iteration);
/**
* Format for end-of-iteration.
*
* @param benchParams name of benchmark
* @param params iteration params in use
* @param iteration iteration-number
* @param data result of iteration
*/
void iterationResult(BenchmarkParams benchParams, IterationParams params, int iteration, IterationResult data);
/**
* Format for start-of-benchmark output.
* @param benchParams benchmark params
*/
void startBenchmark(BenchmarkParams benchParams);
/**
* Format for end-of-benchmark.
*
* @param result statistics of the run
*/
void endBenchmark(BenchmarkResult result);
/**
* Format for start-of-benchmark output.
*/
void startRun();
/**
* Format for end-of-benchmark.
* @param result benchmark results
*/
void endRun(Collection<RunResult> result);
/* ------------- RAW OUTPUT METHODS ------------------- */
void print(String s);
void println(String s);
void flush();
void close();
void verbosePrintln(String s);
void write(int b);
void write(byte[] b) throws IOException;
}
| 3,056 | 29.267327 | 115 | java |
jmh | jmh-master/jmh-core/src/main/java/org/openjdk/jmh/runner/format/OutputFormatFactory.java | /*
* Copyright (c) 2005, 2014, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package org.openjdk.jmh.runner.format;
import org.openjdk.jmh.runner.options.VerboseMode;
import java.io.PrintStream;
public class OutputFormatFactory {
/**
* Factory method for OutputFormat instances
*
* @param out output stream to use
* @param mode how much verbosity to use
* @return a new OutputFormat instance of given type
*/
public static OutputFormat createFormatInstance(PrintStream out, VerboseMode mode) {
switch (mode) {
case SILENT:
return new SilentFormat(out, mode);
case NORMAL:
case EXTRA:
return new TextReportFormat(out, mode);
default:
throw new IllegalArgumentException("Mode " + mode + " not found!");
}
}
}
| 2,003 | 36.811321 | 88 | java |
jmh | jmh-master/jmh-core/src/main/java/org/openjdk/jmh/runner/format/SilentFormat.java | /*
* Copyright (c) 2005, 2013, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package org.openjdk.jmh.runner.format;
import org.openjdk.jmh.infra.BenchmarkParams;
import org.openjdk.jmh.infra.IterationParams;
import org.openjdk.jmh.results.BenchmarkResult;
import org.openjdk.jmh.results.IterationResult;
import org.openjdk.jmh.results.RunResult;
import org.openjdk.jmh.runner.options.VerboseMode;
import java.io.PrintStream;
import java.util.Collection;
/**
* Silent format, does nothing.
*/
class SilentFormat extends AbstractOutputFormat {
public SilentFormat(PrintStream out, VerboseMode verbose) {
super(out, verbose);
}
@Override
public void startRun() {
}
@Override
public void endRun(Collection<RunResult> results) {
}
@Override
public void startBenchmark(BenchmarkParams benchmarkParams) {
}
@Override
public void endBenchmark(BenchmarkResult result) {
}
@Override
public void iteration(BenchmarkParams benchmarkParams, IterationParams params, int iteration) {
}
@Override
public void iterationResult(BenchmarkParams benchmarkParams, IterationParams params, int iteration, IterationResult data) {
}
@Override
public void print(String s) {
}
@Override
public void println(String s) {
}
@Override
public void verbosePrintln(String s) {
}
}
| 2,528 | 27.41573 | 127 | java |
jmh | jmh-master/jmh-core/src/main/java/org/openjdk/jmh/runner/format/SupportedVMs.java | /*
* Copyright (c) 2018, Red Hat Inc. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package org.openjdk.jmh.runner.format;
/**
* JMH VM support tester
*/
class SupportedVMs {
static final String[] FULL_SUPPORT = {
"OpenJDK",
"HotSpot",
};
static final String[] EXPERIMENTAL_SUPPORT = {
"Zing",
"GraalVM",
};
public static Level supportLevel(String name) {
for (String vmName : FULL_SUPPORT) {
if (name.contains(vmName)) return Level.FULL;
}
for (String vmName : EXPERIMENTAL_SUPPORT) {
if (name.contains(vmName)) return Level.EXPERIMENTAL;
}
return Level.NONE;
}
public enum Level {
FULL,
EXPERIMENTAL,
NONE,
}
}
| 1,895 | 31.135593 | 76 | java |
jmh | jmh-master/jmh-core/src/main/java/org/openjdk/jmh/runner/format/TextReportFormat.java | /*
* Copyright (c) 2005, 2013, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package org.openjdk.jmh.runner.format;
import org.openjdk.jmh.annotations.Mode;
import org.openjdk.jmh.infra.BenchmarkParams;
import org.openjdk.jmh.infra.IterationParams;
import org.openjdk.jmh.results.BenchmarkResult;
import org.openjdk.jmh.results.IterationResult;
import org.openjdk.jmh.results.Result;
import org.openjdk.jmh.results.RunResult;
import org.openjdk.jmh.results.format.ResultFormatFactory;
import org.openjdk.jmh.results.format.ResultFormatType;
import org.openjdk.jmh.runner.CompilerHints;
import org.openjdk.jmh.runner.IterationType;
import org.openjdk.jmh.runner.options.TimeValue;
import org.openjdk.jmh.runner.options.VerboseMode;
import org.openjdk.jmh.util.Utils;
import java.io.PrintStream;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;
/**
* TextReportFormat implementation of OutputFormat.
*/
class TextReportFormat extends AbstractOutputFormat {
public TextReportFormat(PrintStream out, VerboseMode verbose) {
super(out, verbose);
}
@Override
public void startBenchmark(BenchmarkParams params) {
String opts = Utils.join(params.getJvmArgs(), " ");
if (opts.trim().isEmpty()) {
opts = "<none>";
}
println("# JMH version: " + params.getJmhVersion());
println("# VM version: JDK " + params.getJdkVersion() + ", " + params.getVmName() + ", " + params.getVmVersion());
switch (SupportedVMs.supportLevel(params.getVmName())) {
case FULL:
break;
case EXPERIMENTAL:
println("# *** WARNING: JMH support for this VM is experimental. Be extra careful with the produced data.");
break;
case NONE:
println("# *** WARNING: This VM is not supported by JMH. The produced benchmark data can be completely wrong.");
break;
default:
throw new IllegalStateException("Unknown support level");
}
println("# VM invoker: " + params.getJvm());
println("# VM options: " + opts);
CompilerHints.printHints(out);
IterationParams warmup = params.getWarmup();
if (warmup.getCount() > 0) {
out.println("# Warmup: " + warmup.getCount() + " iterations, " +
warmup.getTime() + " each" +
(warmup.getBatchSize() <= 1 ? "" : ", " + warmup.getBatchSize() + " calls per op"));
} else {
out.println("# Warmup: <none>");
}
IterationParams measurement = params.getMeasurement();
if (measurement.getCount() > 0) {
out.println("# Measurement: " + measurement.getCount() + " iterations, " +
measurement.getTime() + " each" +
(measurement.getBatchSize() <= 1 ? "" : ", " + measurement.getBatchSize() + " calls per op"));
} else {
out.println("# Measurement: <none>");
}
TimeValue timeout = params.getTimeout();
boolean timeoutWarning = (timeout.convertTo(TimeUnit.NANOSECONDS) <= measurement.getTime().convertTo(TimeUnit.NANOSECONDS)) ||
(timeout.convertTo(TimeUnit.NANOSECONDS) <= warmup.getTime().convertTo(TimeUnit.NANOSECONDS));
out.println("# Timeout: " + timeout + " per iteration" + (timeoutWarning ? ", ***WARNING: The timeout might be too low!***" : ""));
out.print("# Threads: " + params.getThreads() + " " + getThreadsString(params.getThreads()));
if (!params.getThreadGroupLabels().isEmpty()) {
int[] tg = params.getThreadGroups();
// TODO: Make params.getThreadGroupLabels return List
List<String> labels = new ArrayList<>(params.getThreadGroupLabels());
String[] ss = new String[tg.length];
for (int cnt = 0; cnt < tg.length; cnt++) {
ss[cnt] = tg[cnt] + "x \"" + labels.get(cnt) + "\"";
}
int groupCount = params.getThreads() / Utils.sum(tg);
out.print(" (" + groupCount + " " + getGroupsString(groupCount) + "; " + Utils.join(ss, ", ") + " in each group)");
}
out.println(params.shouldSynchIterations() ?
", will synchronize iterations" :
(params.getMode() == Mode.SingleShotTime) ? "" : ", ***WARNING: Synchronize iterations are disabled!***");
out.println("# Benchmark mode: " + params.getMode().longLabel());
out.println("# Benchmark: " + params.getBenchmark());
if (!params.getParamsKeys().isEmpty()) {
String s = "";
boolean isFirst = true;
for (String k : params.getParamsKeys()) {
if (isFirst) {
isFirst = false;
} else {
s += ", ";
}
s += k + " = " + params.getParam(k);
}
out.println("# Parameters: (" + s + ")");
}
}
@Override
public void iteration(BenchmarkParams benchmarkParams, IterationParams params, int iteration) {
switch (params.getType()) {
case WARMUP:
out.print(String.format("# Warmup Iteration %3d: ", iteration));
break;
case MEASUREMENT:
out.print(String.format("Iteration %3d: ", iteration));
break;
default:
throw new IllegalStateException("Unknown iteration type: " + params.getType());
}
out.flush();
}
protected static String getThreadsString(int t) {
if (t > 1) {
return "threads";
} else {
return "thread";
}
}
protected static String getGroupsString(int g) {
if (g > 1) {
return "groups";
} else {
return "group";
}
}
@Override
public void iterationResult(BenchmarkParams benchmParams, IterationParams params, int iteration, IterationResult data) {
StringBuilder sb = new StringBuilder();
sb.append(data.getPrimaryResult().toString());
if (params.getType() == IterationType.MEASUREMENT) {
int prefixLen = String.format("Iteration %3d: ", iteration).length();
Map<String, Result> secondary = data.getSecondaryResults();
if (!secondary.isEmpty()) {
sb.append("\n");
int maxKeyLen = 0;
for (Map.Entry<String, Result> res : secondary.entrySet()) {
maxKeyLen = Math.max(maxKeyLen, res.getKey().length());
}
for (Map.Entry<String, Result> res : secondary.entrySet()) {
sb.append(String.format("%" + prefixLen + "s", ""));
sb.append(String.format(" %-" + (maxKeyLen + 1) + "s %s", res.getKey() + ":", res.getValue()));
sb.append("\n");
}
}
}
out.print(String.format("%s%n", sb.toString()));
out.flush();
}
@Override
public void endBenchmark(BenchmarkResult result) {
out.println();
if (result != null) {
{
Result r = result.getPrimaryResult();
String s = r.extendedInfo();
if (!s.trim().isEmpty()) {
out.println("Result \"" + result.getParams().getBenchmark() + "\":");
out.println(s);
}
}
for (Result r : result.getSecondaryResults().values()) {
String s = r.extendedInfo();
if (!s.trim().isEmpty()) {
out.println("Secondary result \"" + result.getParams().getBenchmark() + ":" + r.getLabel() + "\":");
out.println(s);
}
}
out.println();
}
}
@Override
public void startRun() {
// do nothing
}
@Override
public void endRun(Collection<RunResult> runResults) {
out.println("REMEMBER: The numbers below are just data. To gain reusable insights, you need to follow up on");
out.println("why the numbers are the way they are. Use profilers (see -prof, -lprof), design factorial");
out.println("experiments, perform baseline and negative tests that provide experimental control, make sure");
out.println("the benchmarking environment is safe on JVM/OS/HW level, ask for reviews from the domain experts.");
out.println("Do not assume the numbers tell you what you want them to tell.");
out.println();
CompilerHints.printWarnings(out);
ResultFormatFactory.getInstance(ResultFormatType.TEXT, out).writeOut(runResults);
}
}
| 9,983 | 38.936 | 139 | java |
jmh | jmh-master/jmh-core/src/main/java/org/openjdk/jmh/runner/link/ActionPlanFrame.java | /*
* Copyright (c) 2005, 2013, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package org.openjdk.jmh.runner.link;
import org.openjdk.jmh.runner.ActionPlan;
import java.io.Serializable;
class ActionPlanFrame implements Serializable {
private static final long serialVersionUID = 4652437412096164885L;
private final ActionPlan actionPlan;
public ActionPlanFrame(ActionPlan actionPlan) {
this.actionPlan = actionPlan;
}
public ActionPlan getActionPlan() {
return actionPlan;
}
}
| 1,658 | 36.704545 | 79 | java |
jmh | jmh-master/jmh-core/src/main/java/org/openjdk/jmh/runner/link/BinaryLinkClient.java | /*
* Copyright (c) 2005, 2013, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package org.openjdk.jmh.runner.link;
import org.openjdk.jmh.results.BenchmarkResultMetaData;
import org.openjdk.jmh.results.IterationResult;
import org.openjdk.jmh.runner.ActionPlan;
import org.openjdk.jmh.runner.BenchmarkException;
import org.openjdk.jmh.runner.format.OutputFormat;
import org.openjdk.jmh.runner.options.Options;
import org.openjdk.jmh.util.FileUtils;
import org.openjdk.jmh.util.Utils;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
import java.io.PrintStream;
import java.io.Serializable;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.net.Socket;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public final class BinaryLinkClient {
private static final int RESET_EACH = Integer.getInteger("jmh.link.resetEach", 100);
private static final int BUFFER_SIZE = Integer.getInteger("jmh.link.bufferSize", 64*1024);
private final Object lock;
private final Socket clientSocket;
private final ObjectOutputStream oos;
private final ObjectInputStream ois;
private final ForwardingPrintStream streamErr;
private final ForwardingPrintStream streamOut;
private final OutputFormat outputFormat;
private volatile boolean failed;
private int resetToGo;
private final List<Serializable> delayedFrames;
private boolean inFrame;
public BinaryLinkClient(String hostName, int hostPort) throws IOException {
this.lock = new Object();
this.clientSocket = new Socket(hostName, hostPort);
// Initialize the OOS first, and flush, letting the other party read the stream header.
this.oos = new ObjectOutputStream(new BufferedOutputStream(clientSocket.getOutputStream(), BUFFER_SIZE));
this.oos.flush();
this.ois = new ObjectInputStream(new BufferedInputStream(clientSocket.getInputStream(), BUFFER_SIZE));
this.streamErr = new ForwardingPrintStream(OutputFrame.Type.ERR);
this.streamOut = new ForwardingPrintStream(OutputFrame.Type.OUT);
this.outputFormat = (OutputFormat) Proxy.newProxyInstance(
Thread.currentThread().getContextClassLoader(),
new Class[]{OutputFormat.class},
(proxy, method, args) -> {
pushFrame(new OutputFormatFrame(ClassConventions.getMethodName(method), args));
return null; // expect null
}
);
this.delayedFrames = new ArrayList<>();
}
private void pushFrame(Serializable frame) throws IOException {
if (failed) {
throw new IOException("Link had failed already");
}
// It is important to reset the OOS to avoid garbage buildup in internal identity
// tables. However, we cannot do that after each frame since the huge referenced
// objects like benchmark and iteration parameters will be duplicated on the receiver
// side. This is why we reset only each RESET_EACH frames.
//
// It is as much as important to flush the stream to let the other party know we
// pushed something out.
synchronized (lock) {
if (inFrame) {
// Something had produced this frame while we were writing another one.
// Most probably, stdout/stderr message was produced when serializing data.
// Delay this frame until the write is over, and let the original writer to
// pick it up later.
delayedFrames.add(frame);
return;
}
try {
inFrame = true;
if (resetToGo-- < 0) {
oos.reset();
resetToGo = RESET_EACH;
}
oos.writeObject(frame);
oos.flush();
// Do all delayed frames now. On the off-chance their writes produce more frames,
// drain them recursively.
while (!delayedFrames.isEmpty()) {
List<Serializable> frames = new ArrayList<>(delayedFrames);
delayedFrames.clear();
for (Serializable f : frames) {
oos.writeObject(f);
}
oos.flush();
}
} catch (IOException e) {
failed = true;
throw e;
} finally {
inFrame = false;
}
}
}
private Object readFrame() throws IOException, ClassNotFoundException {
try {
return ois.readObject();
} catch (ClassNotFoundException | IOException ex) {
failed = true;
throw ex;
}
}
public void close() throws IOException {
// BinaryLinkClient (BLC) should not acquire the BLC lock while dealing with
// ForwardingPrintStream (FPS): if there is a pending operation in FPS,
// and it writes something out, it will acquire the BLC lock after acquiring
// FPS lock => deadlock. Let FPS figure this one out on its own.
FileUtils.safelyClose(streamErr);
FileUtils.safelyClose(streamOut);
synchronized (lock) {
oos.writeObject(new FinishingFrame());
FileUtils.safelyClose(ois);
FileUtils.safelyClose(oos);
clientSocket.close();
}
}
public Options handshake() throws IOException, ClassNotFoundException {
synchronized (lock) {
pushFrame(new HandshakeInitFrame(Utils.getPid()));
Object reply = readFrame();
if (reply instanceof HandshakeResponseFrame) {
return (((HandshakeResponseFrame) reply).getOpts());
} else {
throw new IllegalStateException("Got the erroneous reply: " + reply);
}
}
}
public ActionPlan requestPlan() throws IOException, ClassNotFoundException {
synchronized (lock) {
pushFrame(new InfraFrame(InfraFrame.Type.ACTION_PLAN_REQUEST));
Object reply = readFrame();
if (reply instanceof ActionPlanFrame) {
return ((ActionPlanFrame) reply).getActionPlan();
} else {
throw new IllegalStateException("Got the erroneous reply: " + reply);
}
}
}
public void pushResults(IterationResult res) throws IOException {
pushFrame(new ResultsFrame(res));
}
public void pushException(BenchmarkException error) throws IOException {
pushFrame(new ExceptionFrame(error));
}
public void pushResultMetadata(BenchmarkResultMetaData res) throws IOException {
pushFrame(new ResultMetadataFrame(res));
}
public PrintStream getOutStream() {
return streamOut;
}
public PrintStream getErrStream() {
return streamErr;
}
public OutputFormat getOutputFormat() {
return outputFormat;
}
class ForwardingPrintStream extends PrintStream {
public ForwardingPrintStream(final OutputFrame.Type type) {
super(new OutputStream() {
@Override
public void write(int b) throws IOException {
pushFrame(new OutputFrame(type, new byte[]{(byte) (b & 0xFF)}));
}
@Override
public void write(byte[] b) throws IOException {
pushFrame(new OutputFrame(type, Arrays.copyOf(b, b.length)));
}
@Override
public void write(byte[] b, int off, int len) throws IOException {
pushFrame(new OutputFrame(type, Arrays.copyOfRange(b, off, len + off)));
}
});
}
}
}
| 9,185 | 36.647541 | 113 | java |
jmh | jmh-master/jmh-core/src/main/java/org/openjdk/jmh/runner/link/BinaryLinkServer.java | /*
* Copyright (c) 2005, 2013, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package org.openjdk.jmh.runner.link;
import org.openjdk.jmh.results.BenchmarkResultMetaData;
import org.openjdk.jmh.results.IterationResult;
import org.openjdk.jmh.runner.ActionPlan;
import org.openjdk.jmh.runner.BenchmarkException;
import org.openjdk.jmh.runner.Defaults;
import org.openjdk.jmh.runner.format.OutputFormat;
import org.openjdk.jmh.runner.options.Options;
import org.openjdk.jmh.runner.options.VerboseMode;
import org.openjdk.jmh.util.Utils;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.EOFException;
import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.SocketException;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.atomic.AtomicReference;
/**
* Accepts the binary data from the forked VM and pushes it to parent VM
* as appropriate. This server assumes there is only the one and only
* client at any given point of time.
*/
public final class BinaryLinkServer {
private static final int BUFFER_SIZE = Integer.getInteger("jmh.link.bufferSize", 64*1024);
private final Options opts;
private final OutputFormat out;
private final Map<String, Method> methods;
private final Set<String> forbidden;
private final Acceptor acceptor;
private final AtomicReference<Handler> handler;
private final AtomicReference<List<IterationResult>> results;
private final AtomicReference<BenchmarkResultMetaData> metadata;
private final AtomicReference<BenchmarkException> exception;
private final AtomicReference<ActionPlan> plan;
private volatile long clientPid;
public BinaryLinkServer(Options opts, OutputFormat out) throws IOException {
this.opts = opts;
this.out = out;
this.methods = new HashMap<>();
this.forbidden = new HashSet<>();
// enumerate methods
for (Method m : OutputFormat.class.getMethods()) {
// start/end run callbacks are banned, since their effects are enforced by parent instead
if (m.getName().equals("startRun")) { forbidden.add(ClassConventions.getMethodName(m)); }
if (m.getName().equals("endRun")) { forbidden.add(ClassConventions.getMethodName(m)); }
Method prev = methods.put(ClassConventions.getMethodName(m), m);
if (prev != null) {
out.println("WARNING: Duplicate methods: " + m + " vs. " + prev);
throw new IllegalStateException("WARNING: Duplicate methods: " + m + " vs. " + prev);
}
}
acceptor = new Acceptor();
acceptor.start();
handler = new AtomicReference<>();
metadata = new AtomicReference<>();
results = new AtomicReference<>(new ArrayList<>());
exception = new AtomicReference<>();
plan = new AtomicReference<>();
}
public void terminate() {
acceptor.close();
Handler h = handler.getAndSet(null);
if (h != null) {
h.close();
}
try {
acceptor.join();
if (h != null) {
h.join();
}
} catch (InterruptedException e) {
// ignore
}
}
public void waitFinish() {
Handler h = handler.getAndSet(null);
if (h != null) {
try {
h.join();
} catch (InterruptedException e) {
// ignore
}
}
}
public BenchmarkException getException() {
return exception.getAndSet(null);
}
public List<IterationResult> getResults() {
List<IterationResult> res = results.getAndSet(new ArrayList<>());
if (res != null) {
return res;
} else {
throw new IllegalStateException("Acquiring the null result");
}
}
public BenchmarkResultMetaData getMetadata() {
return metadata.getAndSet(null);
}
public void setPlan(ActionPlan actionPlan) {
this.plan.set(actionPlan);
}
private InetAddress getListenAddress() {
// Try to use user-provided override first.
String addr = System.getProperty("jmh.link.address");
if (addr != null) {
try {
return InetAddress.getByName(addr);
} catch (UnknownHostException e) {
// override failed, notify user
throw new IllegalStateException("Can not initialize binary link.", e);
}
}
// Auto-detection should try to use JDK 7+ method first, it is more reliable.
try {
Method m = InetAddress.class.getMethod("getLoopbackAddress");
return (InetAddress) m.invoke(null);
} catch (InvocationTargetException | IllegalAccessException | NoSuchMethodException e) {
// shun
}
// Otherwise open up the special loopback.
// (It can only fail for the obscure reason)
try {
return InetAddress.getByAddress(new byte[] {127, 0, 0, 1});
} catch (UnknownHostException e) {
// shun
}
// Last resort. Open the local host: this resolves
// the machine name, and not reliable on mis-configured
// hosts, but there is nothing else we can try.
try {
return InetAddress.getLocalHost();
} catch (UnknownHostException e) {
throw new IllegalStateException("Can not find the address to bind to.", e);
}
}
private int getListenPort() {
return Integer.getInteger("jmh.link.port", 0);
}
public long getClientPid() {
return clientPid;
}
private final class Acceptor extends Thread {
private final ServerSocket server;
private final InetAddress listenAddress;
public Acceptor() throws IOException {
listenAddress = getListenAddress();
server = new ServerSocket(getListenPort(), 50, listenAddress);
}
@Override
public void run() {
try {
while (!Thread.interrupted()) {
Socket clientSocket = server.accept();
Handler r = new Handler(clientSocket);
if (!handler.compareAndSet(null, r)) {
throw new IllegalStateException("The handler is already registered");
}
r.start();
}
} catch (SocketException e) {
// assume this is "Socket closed", return
} catch (IOException e) {
throw new IllegalStateException(e);
} finally {
close();
}
}
public String getHost() {
return listenAddress.getHostAddress();
}
public int getPort() {
// Poll the actual listen port, in case it is ephemeral
return server.getLocalPort();
}
public void close() {
try {
server.close();
} catch (IOException e) {
// do nothing
}
}
}
public String getHost() {
return acceptor.getHost();
}
public int getPort() {
return acceptor.getPort();
}
private final class Handler extends Thread {
private final InputStream is;
private final Socket socket;
private ObjectInputStream ois;
private final OutputStream os;
private ObjectOutputStream oos;
public Handler(Socket socket) throws IOException {
this.socket = socket;
this.is = socket.getInputStream();
this.os = socket.getOutputStream();
// eager OOS initialization, let the other party read the stream header
oos = new ObjectOutputStream(new BufferedOutputStream(os, BUFFER_SIZE));
oos.flush();
}
@Override
public void run() {
try {
// late OIS initialization, otherwise we'll block reading the header
ois = new ObjectInputStream(new BufferedInputStream(is, BUFFER_SIZE));
Object obj;
while ((obj = ois.readObject()) != null) {
if (obj instanceof OutputFormatFrame) {
handleOutputFormat((OutputFormatFrame) obj);
}
if (obj instanceof InfraFrame) {
handleInfra((InfraFrame) obj);
}
if (obj instanceof HandshakeInitFrame) {
handleHandshake((HandshakeInitFrame) obj);
}
if (obj instanceof ResultsFrame) {
handleResults((ResultsFrame) obj);
}
if (obj instanceof ExceptionFrame) {
handleException((ExceptionFrame) obj);
}
if (obj instanceof OutputFrame) {
handleOutput((OutputFrame) obj);
}
if (obj instanceof ResultMetadataFrame) {
handleResultMetadata((ResultMetadataFrame) obj);
}
if (obj instanceof FinishingFrame) {
// close the streams
break;
}
}
} catch (EOFException e) {
// ignore
} catch (Exception e) {
out.println("<binary link had failed, forked VM corrupted the stream? Use " + VerboseMode.EXTRA + " verbose to print exception>");
if (opts.verbosity().orElse(Defaults.VERBOSITY).equalsOrHigherThan(VerboseMode.EXTRA)) {
out.println(Utils.throwableToString(e));
}
} finally {
close();
}
}
private void handleResultMetadata(ResultMetadataFrame obj) {
metadata.set(obj.getMD());
}
private void handleOutput(OutputFrame obj) {
try {
switch (obj.getType()) {
case OUT:
System.out.write(obj.getData());
break;
case ERR:
System.err.write(obj.getData());
break;
}
} catch (IOException e) {
// swallow
}
}
private void handleException(ExceptionFrame obj) {
exception.set(obj.getError());
}
private void handleResults(ResultsFrame obj) {
results.get().add(obj.getRes());
}
private void handleHandshake(HandshakeInitFrame obj) throws IOException {
clientPid = obj.getPid();
oos.writeObject(new HandshakeResponseFrame(opts));
oos.flush();
}
private void handleInfra(InfraFrame req) throws IOException {
switch (req.getType()) {
case ACTION_PLAN_REQUEST:
oos.writeObject(new ActionPlanFrame(plan.get()));
oos.flush();
break;
default:
throw new IllegalStateException("Unknown infrastructure request: " + req);
}
}
private boolean handleOutputFormat(OutputFormatFrame frame) throws IllegalAccessException, InvocationTargetException {
Method m = methods.get(frame.method);
if (m == null) {
out.println("WARNING: Unknown method to forward: " + frame.method);
return true;
}
if (forbidden.contains(frame.method)) {
return true;
}
m.invoke(out, frame.args);
return false;
}
public void close() {
try {
socket.close();
} catch (IOException e) {
// ignore
}
}
}
}
| 13,634 | 33.345088 | 146 | java |
jmh | jmh-master/jmh-core/src/main/java/org/openjdk/jmh/runner/link/ClassConventions.java | /*
* Copyright (c) 2005, 2013, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package org.openjdk.jmh.runner.link;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;
class ClassConventions {
private static final Map<Method, String> METHOD_NAMES = new HashMap<>();
public static String getMethodName(Method m) {
String result = METHOD_NAMES.get(m);
if (result == null) {
StringBuilder builder = new StringBuilder();
builder.append(m.getName());
for (Class<?> paramType : m.getParameterTypes()) {
builder.append(paramType.getName());
builder.append(",");
}
result = builder.toString();
METHOD_NAMES.put(m, result);
}
return result;
}
}
| 1,952 | 37.294118 | 79 | java |
jmh | jmh-master/jmh-core/src/main/java/org/openjdk/jmh/runner/link/ExceptionFrame.java | /*
* Copyright (c) 2005, 2014, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package org.openjdk.jmh.runner.link;
import org.openjdk.jmh.runner.BenchmarkException;
import java.io.Serializable;
class ExceptionFrame implements Serializable {
private static final long serialVersionUID = 5595622047639653401L;
private final BenchmarkException error;
public ExceptionFrame(BenchmarkException error) {
this.error = error;
}
public BenchmarkException getError() {
return error;
}
}
| 1,658 | 36.704545 | 79 | java |
jmh | jmh-master/jmh-core/src/main/java/org/openjdk/jmh/runner/link/FinishingFrame.java | /*
* Copyright (c) 2005, 2013, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package org.openjdk.jmh.runner.link;
import java.io.Serializable;
class FinishingFrame implements Serializable {
private static final long serialVersionUID = 2309975914801631608L;
}
| 1,401 | 42.8125 | 79 | java |
jmh | jmh-master/jmh-core/src/main/java/org/openjdk/jmh/runner/link/HandshakeInitFrame.java | /*
* Copyright (c) 2005, 2013, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package org.openjdk.jmh.runner.link;
import java.io.Serializable;
class HandshakeInitFrame implements Serializable {
private static final long serialVersionUID = 2082214387637725282L;
private final long pid;
public HandshakeInitFrame(long pid) {
this.pid = pid;
}
public long getPid() {
return pid;
}
}
| 1,561 | 36.190476 | 79 | java |
jmh | jmh-master/jmh-core/src/main/java/org/openjdk/jmh/runner/link/HandshakeResponseFrame.java | /*
* Copyright (c) 2005, 2013, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package org.openjdk.jmh.runner.link;
import org.openjdk.jmh.runner.options.Options;
import java.io.Serializable;
class HandshakeResponseFrame implements Serializable {
private static final long serialVersionUID = 2082214387637725282L;
private final Options opts;
public HandshakeResponseFrame(Options opts) {
this.opts = opts;
}
public Options getOpts() {
return opts;
}
}
| 1,632 | 36.113636 | 79 | java |
jmh | jmh-master/jmh-core/src/main/java/org/openjdk/jmh/runner/link/InfraFrame.java | /*
* Copyright (c) 2005, 2013, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package org.openjdk.jmh.runner.link;
import java.io.Serializable;
class InfraFrame implements Serializable {
private static final long serialVersionUID = 6341776120773421805L;
private final Type type;
public InfraFrame(Type type) {
this.type = type;
}
public Type getType() {
return type;
}
public enum Type {
ACTION_PLAN_REQUEST,
}
}
| 1,610 | 34.021739 | 79 | java |
jmh | jmh-master/jmh-core/src/main/java/org/openjdk/jmh/runner/link/OutputFormatFrame.java | /*
* Copyright (c) 2005, 2013, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package org.openjdk.jmh.runner.link;
import java.io.Serializable;
/**
* Encapsulates the OutputFormat call
* - method name
* - arguments (assumed to be serializable)
*/
class OutputFormatFrame implements Serializable {
private static final long serialVersionUID = -7151852354574635295L;
public final String method;
public final Object[] args;
public OutputFormatFrame(String method, Object[] args) {
this.method = method;
this.args = args;
}
}
| 1,704 | 37.75 | 79 | java |
jmh | jmh-master/jmh-core/src/main/java/org/openjdk/jmh/runner/link/OutputFrame.java | /*
* Copyright (c) 2005, 2014, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package org.openjdk.jmh.runner.link;
import java.io.Serializable;
class OutputFrame implements Serializable {
private static final long serialVersionUID = 8570795333046092668L;
private final Type type;
private final byte[] data;
public OutputFrame(Type type, byte[] data) {
this.type = type;
this.data = data;
}
public byte[] getData() {
return data;
}
public Type getType() {
return type;
}
public enum Type {
OUT,
ERR,
}
}
| 1,738 | 31.203704 | 79 | java |
jmh | jmh-master/jmh-core/src/main/java/org/openjdk/jmh/runner/link/ResultMetadataFrame.java | /*
* Copyright (c) 2005, 2013, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package org.openjdk.jmh.runner.link;
import org.openjdk.jmh.results.BenchmarkResultMetaData;
import java.io.Serializable;
class ResultMetadataFrame implements Serializable {
private static final long serialVersionUID = -5627086531281515824L;
private final BenchmarkResultMetaData md;
public ResultMetadataFrame(BenchmarkResultMetaData md) {
this.md = md;
}
public BenchmarkResultMetaData getMD() {
return md;
}
}
| 1,672 | 37.022727 | 79 | java |
jmh | jmh-master/jmh-core/src/main/java/org/openjdk/jmh/runner/link/ResultsFrame.java | /*
* Copyright (c) 2005, 2013, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package org.openjdk.jmh.runner.link;
import org.openjdk.jmh.results.IterationResult;
import java.io.Serializable;
class ResultsFrame implements Serializable {
private static final long serialVersionUID = -5627086531281515824L;
private final IterationResult res;
public ResultsFrame(IterationResult res) {
this.res = res;
}
public IterationResult getRes() {
return res;
}
}
| 1,632 | 36.113636 | 79 | java |
jmh | jmh-master/jmh-core/src/main/java/org/openjdk/jmh/runner/options/ChainedOptionsBuilder.java | /*
* Copyright (c) 2005, 2013, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package org.openjdk.jmh.runner.options;
import org.openjdk.jmh.annotations.Mode;
import org.openjdk.jmh.profile.Profiler;
import org.openjdk.jmh.results.format.ResultFormatType;
import java.util.concurrent.TimeUnit;
public interface ChainedOptionsBuilder {
/**
* Produce the final Options
* @return options object.
*/
Options build();
/**
* Override the defaults from the given option.
* You may use this only once.
*
* @param other options to base on
* @return builder
*/
ChainedOptionsBuilder parent(Options other);
/**
* Include benchmark in the run
* (Can be used multiple times)
*
* @param regexp to match benchmarks against
* @return builder
* @see org.openjdk.jmh.runner.Defaults#INCLUDE_BENCHMARKS
*/
ChainedOptionsBuilder include(String regexp);
/**
* Exclude benchmarks from the run
* (Can be used multiple times)
*
* @param regexp to match benchmark against
* @return builder
*/
ChainedOptionsBuilder exclude(String regexp);
/**
* ResultFormatType to use in the run
* @param type resultformat type
* @return builder
* @see org.openjdk.jmh.runner.Defaults#RESULT_FORMAT
*/
ChainedOptionsBuilder resultFormat(ResultFormatType type);
/**
* Output filename to write the run log to
* @param filename file name
* @return builder
*/
ChainedOptionsBuilder output(String filename);
/**
* Output filename to write the result to
* @param filename file name
* @return builder
* @see org.openjdk.jmh.runner.Defaults#RESULT_FILE_PREFIX
*/
ChainedOptionsBuilder result(String filename);
/**
* Should do GC between measurementIterations?
* @param value flag
* @return builder
* @see org.openjdk.jmh.runner.Defaults#DO_GC
*/
ChainedOptionsBuilder shouldDoGC(boolean value);
/**
* Add the profiler in the run
* @param profiler profiler class
* @return builder
*/
ChainedOptionsBuilder addProfiler(Class<? extends Profiler> profiler);
/**
* Add the profiler in the run
* @param profiler profiler class
* @param initLine profiler options initialization line
* @return builder
*/
ChainedOptionsBuilder addProfiler(Class<? extends Profiler> profiler, String initLine);
/**
* Add the profiler in the run
* @param profiler profiler class name, or profiler alias
* @return builder
*/
ChainedOptionsBuilder addProfiler(String profiler);
/**
* Add the profiler in the run
* @param profiler profiler class name, or profiler alias
* @param initLine profiler options initialization line
* @return builder
*/
ChainedOptionsBuilder addProfiler(String profiler, String initLine);
/**
* Control verbosity level.
* @param mode flag
* @return builder
* @see org.openjdk.jmh.runner.Defaults#VERBOSITY
*/
ChainedOptionsBuilder verbosity(VerboseMode mode);
/**
* Should fail on first benchmark error?
* @param value flag
* @return builder
* @see org.openjdk.jmh.runner.Defaults#FAIL_ON_ERROR
*/
ChainedOptionsBuilder shouldFailOnError(boolean value);
/**
* Number of threads to run the benchmark in
* @param count number of threads
* @return builder
* @see org.openjdk.jmh.annotations.Threads
* @see org.openjdk.jmh.runner.Defaults#THREADS
*/
ChainedOptionsBuilder threads(int count);
/**
* Subgroups thread distribution.
* @param groups thread distribution
* @return builder
* @see org.openjdk.jmh.annotations.Group
* @see org.openjdk.jmh.annotations.GroupThreads
*/
ChainedOptionsBuilder threadGroups(int... groups);
/**
* Should synchronize measurementIterations?
* @param value flag
* @return builder
* @see org.openjdk.jmh.runner.Defaults#SYNC_ITERATIONS
*/
ChainedOptionsBuilder syncIterations(boolean value);
/**
* How many warmup iterations to do?
* @param value flag
* @return builder
* @see org.openjdk.jmh.annotations.Warmup
* @see org.openjdk.jmh.runner.Defaults#WARMUP_ITERATIONS
* @see org.openjdk.jmh.runner.Defaults#WARMUP_ITERATIONS_SINGLESHOT
*/
ChainedOptionsBuilder warmupIterations(int value);
/**
* How large warmup batchSize should be?
* @param value batch size
* @return builder
* @see org.openjdk.jmh.annotations.Warmup
* @see org.openjdk.jmh.runner.Defaults#WARMUP_BATCHSIZE
*/
ChainedOptionsBuilder warmupBatchSize(int value);
/**
* How long each warmup iteration should take?
* @param value time
* @return builder
* @see org.openjdk.jmh.annotations.Warmup
* @see org.openjdk.jmh.runner.Defaults#WARMUP_TIME
*/
ChainedOptionsBuilder warmupTime(TimeValue value);
/**
* Warmup mode to use
* @param mode to use
* @return builder
* @see org.openjdk.jmh.runner.Defaults#WARMUP_MODE
*/
ChainedOptionsBuilder warmupMode(WarmupMode mode);
/**
* What other benchmarks to warmup along the way
* @param regexp to match benchmarks against
* @return builder
*/
ChainedOptionsBuilder includeWarmup(String regexp);
/**
* How many measurement measurementIterations to do
* @param count number of iterations
* @return builder
* @see org.openjdk.jmh.annotations.Measurement
* @see org.openjdk.jmh.runner.Defaults#MEASUREMENT_ITERATIONS
* @see org.openjdk.jmh.runner.Defaults#MEASUREMENT_ITERATIONS_SINGLESHOT
*/
ChainedOptionsBuilder measurementIterations(int count);
/**
* How large measurement batchSize should be?
* @param value batch size
* @return builder
* @see org.openjdk.jmh.annotations.Measurement
* @see org.openjdk.jmh.runner.Defaults#MEASUREMENT_BATCHSIZE
*/
ChainedOptionsBuilder measurementBatchSize(int value);
/**
* How long each measurement iteration should take?
* @param value time
* @return builder
* @see org.openjdk.jmh.annotations.Measurement
* @see org.openjdk.jmh.runner.Defaults#MEASUREMENT_TIME
*/
ChainedOptionsBuilder measurementTime(TimeValue value);
/**
* Benchmark mode.
* (Can be used multiple times)
*
* @param mode benchmark mode
* @return builder
* @see org.openjdk.jmh.annotations.BenchmarkMode
* @see org.openjdk.jmh.runner.Defaults#BENCHMARK_MODE
*/
ChainedOptionsBuilder mode(Mode mode);
/**
* Timeunit to use in results
* @param tu time unit
* @return builder
* @see org.openjdk.jmh.annotations.OutputTimeUnit
* @see org.openjdk.jmh.runner.Defaults#OUTPUT_TIMEUNIT
*/
ChainedOptionsBuilder timeUnit(TimeUnit tu);
/**
* Operations per invocation.
* @param value operations per invocation.
* @return builder
* @see org.openjdk.jmh.annotations.OperationsPerInvocation
* @see org.openjdk.jmh.runner.Defaults#OPS_PER_INVOCATION
*/
ChainedOptionsBuilder operationsPerInvocation(int value);
/**
* Number of forks to use in the run
* @param value number of forks
* @return builder
* @see org.openjdk.jmh.annotations.Fork
* @see org.openjdk.jmh.runner.Defaults#MEASUREMENT_FORKS
*/
ChainedOptionsBuilder forks(int value);
/**
* Number of ignored forks
* @param value number of ignored forks
* @return builder
* @see org.openjdk.jmh.annotations.Fork
* @see org.openjdk.jmh.runner.Defaults#WARMUP_FORKS
*/
ChainedOptionsBuilder warmupForks(int value);
/**
* Forked JVM to use.
*
* @param path path to /bin/java
* @return builder
*/
ChainedOptionsBuilder jvm(String path);
/**
* Forked JVM arguments.
*
* @param value arguments to add to the run
* @return builder
* @see org.openjdk.jmh.annotations.Fork
*/
ChainedOptionsBuilder jvmArgs(String... value);
/**
* Append forked JVM arguments:
* These options go after other options.
*
* @param value arguments to add to the run
* @return builder
* @see org.openjdk.jmh.annotations.Fork
*/
ChainedOptionsBuilder jvmArgsAppend(String... value);
/**
* Prepend forked JVM arguments:
* These options go before any other options.
*
* @param value arguments to add to the run
* @return builder
* @see org.openjdk.jmh.annotations.Fork
*/
ChainedOptionsBuilder jvmArgsPrepend(String... value);
/**
* Autodetect forked JVM arguments from the parent VM.
* Overrides the jvmArgs(...) value.
*
* @return builder
*/
ChainedOptionsBuilder detectJvmArgs();
/**
* Set benchmark parameter values.
* The parameter values would be taken in the order given by user.
*
* @param name parameter
* @param values sequence of values to set
* @return builder
* @see org.openjdk.jmh.annotations.Param
*/
ChainedOptionsBuilder param(String name, String... values);
/**
* How long to wait for iteration execution?
* @param value time
* @return builder
* @see org.openjdk.jmh.runner.Defaults#TIMEOUT
*/
ChainedOptionsBuilder timeout(TimeValue value);
}
| 10,669 | 29.056338 | 91 | java |
jmh | jmh-master/jmh-core/src/main/java/org/openjdk/jmh/runner/options/CommandLineOptionException.java | /*
* Copyright (c) 2005, 2014, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package org.openjdk.jmh.runner.options;
public class CommandLineOptionException extends Exception {
private static final long serialVersionUID = 4023975483757781721L;
public CommandLineOptionException(String message) {
super(message);
}
public CommandLineOptionException(String message, Throwable cause) {
super(message, cause);
}
}
| 1,585 | 40.736842 | 79 | java |
jmh | jmh-master/jmh-core/src/main/java/org/openjdk/jmh/runner/options/CommandLineOptions.java | /*
* Copyright (c) 2005, 2013, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package org.openjdk.jmh.runner.options;
import joptsimple.*;
import org.openjdk.jmh.annotations.Mode;
import org.openjdk.jmh.profile.ProfilerFactory;
import org.openjdk.jmh.results.format.ResultFormatType;
import org.openjdk.jmh.runner.Defaults;
import org.openjdk.jmh.util.HashMultimap;
import org.openjdk.jmh.util.Multimap;
import org.openjdk.jmh.util.Optional;
import org.openjdk.jmh.util.Utils;
import java.io.IOException;
import java.util.*;
import java.util.concurrent.TimeUnit;
/**
* Class that handles all the command line options.
*/
public class CommandLineOptions implements Options {
private static final long serialVersionUID = 5565183446360224399L;
private final Optional<Integer> iterations;
private final Optional<TimeValue> timeout;
private final Optional<TimeValue> runTime;
private final Optional<Integer> batchSize;
private final Optional<Integer> warmupIterations;
private final Optional<TimeValue> warmupTime;
private final Optional<Integer> warmupBatchSize;
private final List<Mode> benchMode = new ArrayList<>();
private final Optional<Integer> threads;
private final List<Integer> threadGroups = new ArrayList<>();
private final Optional<Boolean> synchIterations;
private final Optional<Boolean> gcEachIteration;
private final Optional<VerboseMode> verbose;
private final Optional<Boolean> failOnError;
private final List<ProfilerConfig> profilers = new ArrayList<>();
private final Optional<TimeUnit> timeUnit;
private final Optional<Integer> opsPerInvocation;
private final List<String> regexps = new ArrayList<>();
private final Optional<Integer> fork;
private final Optional<Integer> warmupFork;
private final Optional<String> output;
private final Optional<String> result;
private final Optional<ResultFormatType> resultFormat;
private final Optional<String> jvm;
private final Optional<Collection<String>> jvmArgs;
private final Optional<Collection<String>> jvmArgsAppend;
private final Optional<Collection<String>> jvmArgsPrepend;
private final List<String> excludes = new ArrayList<>();
private final Optional<WarmupMode> warmupMode;
private final List<String> warmupMicros = new ArrayList<>();
private final Multimap<String, String> params = new HashMultimap<>();
private final boolean list;
private final boolean listWithParams;
private final boolean listResultFormats;
private final boolean help;
private final boolean listProfilers;
private final transient OptionParser parser;
/**
* Parses the given command line.
* @param argv argument list
* @throws CommandLineOptionException if some options are misspelled
*/
public CommandLineOptions(String... argv) throws CommandLineOptionException {
parser = new OptionParser();
parser.formatHelpWith(new OptionFormatter());
OptionSpec<Integer> optMeasureCount = parser.accepts("i", "Number of measurement iterations to do. " +
"Measurement iterations are counted towards the benchmark score. " +
"(default: " + Defaults.MEASUREMENT_ITERATIONS_SINGLESHOT + " for " + Mode.SingleShotTime + ", and " +
Defaults.MEASUREMENT_ITERATIONS + " for all other modes)")
.withRequiredArg().withValuesConvertedBy(IntegerValueConverter.POSITIVE).describedAs("int");
OptionSpec<Integer> optMeasureBatchSize = parser.accepts("bs", "Batch size: number of benchmark method " +
"calls per operation. Some benchmark modes may ignore this setting, please check this separately. " +
"(default: " + Defaults.MEASUREMENT_BATCHSIZE + ")")
.withRequiredArg().withValuesConvertedBy(IntegerValueConverter.POSITIVE).describedAs("int");
OptionSpec<TimeValue> optMeasureTime = parser.accepts("r", "Minimum time to spend at each measurement " +
"iteration. Benchmarks may generally run longer than iteration duration. " +
"(default: " + Defaults.MEASUREMENT_TIME + ")")
.withRequiredArg().ofType(TimeValue.class).describedAs("time");
OptionSpec<Integer> optWarmupCount = parser.accepts("wi", "Number of warmup iterations to do. Warmup " +
"iterations are not counted towards the benchmark score. " +
"(default: " + Defaults.WARMUP_ITERATIONS_SINGLESHOT + " for " + Mode.SingleShotTime + ", and " +
Defaults.WARMUP_ITERATIONS + " for all other modes)")
.withRequiredArg().withValuesConvertedBy(IntegerValueConverter.NON_NEGATIVE).describedAs("int");
OptionSpec<Integer> optWarmupBatchSize = parser.accepts("wbs", "Warmup batch size: number of benchmark " +
"method calls per operation. Some benchmark modes may ignore this setting. " +
"(default: " + Defaults.WARMUP_BATCHSIZE + ")")
.withRequiredArg().withValuesConvertedBy(IntegerValueConverter.POSITIVE).describedAs("int");
OptionSpec<TimeValue> optWarmupTime = parser.accepts("w", "Minimum time to spend at each warmup iteration. " +
"Benchmarks may generally run longer than iteration duration. " +
"(default: " + Defaults.WARMUP_TIME + ")")
.withRequiredArg().ofType(TimeValue.class).describedAs("time");
OptionSpec<TimeValue> optTimeoutTime = parser.accepts("to", "Timeout for benchmark iteration. After reaching " +
"this timeout, JMH will try to interrupt the running tasks. Non-cooperating benchmarks may ignore " +
"this timeout. " +
"(default: " + Defaults.TIMEOUT + ")")
.withRequiredArg().ofType(TimeValue.class).describedAs("time");
OptionSpec<Integer> optThreads = parser.accepts("t", "Number of worker threads to run with. 'max' means the " +
"maximum number of hardware threads available on the machine, figured out by JMH itself. " +
"(default: " + Defaults.THREADS + ")")
.withRequiredArg().withValuesConvertedBy(ThreadsValueConverter.INSTANCE).describedAs("int");
OptionSpec<String> optBenchmarkMode = parser.accepts("bm", "Benchmark mode. Available modes are: " + Mode.getKnown() + ". " +
"(default: " + Defaults.BENCHMARK_MODE + ")")
.withRequiredArg().ofType(String.class).withValuesSeparatedBy(',').describedAs("mode");
OptionSpec<Boolean> optSyncIters = parser.accepts("si", "Should JMH synchronize iterations? This would " +
"significantly lower the noise in multithreaded tests, by making sure the measured part happens only " +
"when all workers are running. " +
"(default: " + Defaults.SYNC_ITERATIONS + ")")
.withRequiredArg().ofType(Boolean.class).describedAs("bool");
OptionSpec<Boolean> optGC = parser.accepts("gc", "Should JMH force GC between iterations? Forcing the GC may " +
"help to lower the noise in GC-heavy benchmarks, at the expense of jeopardizing GC ergonomics " +
"decisions. Use with care. " +
"(default: " + Defaults.DO_GC + ")")
.withRequiredArg().ofType(Boolean.class).describedAs("bool");
OptionSpec<Boolean> optFOE = parser.accepts("foe", "Should JMH fail immediately if any benchmark had " +
"experienced an unrecoverable error? This helps to make quick sanity tests for benchmark suites, as " +
"well as make the automated runs with checking error codes. " +
"(default: " + Defaults.FAIL_ON_ERROR + ")")
.withRequiredArg().ofType(Boolean.class).describedAs("bool");
OptionSpec<String> optVerboseMode = parser.accepts("v", "Verbosity mode. Available modes are: " + Arrays.toString(VerboseMode.values()) + ". " +
"(default: " + Defaults.VERBOSITY + ")")
.withRequiredArg().ofType(String.class).describedAs("mode");
OptionSpec<String> optArgs = parser.nonOptions("Benchmarks to run (regexp+). " +
"(default: " + Defaults.INCLUDE_BENCHMARKS + ")")
.describedAs("regexp+");
OptionSpec<Integer> optForks = parser.accepts("f", "How many times to fork a single benchmark. Use 0 to " +
"disable forking altogether. Warning: disabling forking may have detrimental impact on benchmark and " +
"infrastructure reliability, you might want to use different warmup mode instead. " +
"(default: " + Defaults.MEASUREMENT_FORKS + ")")
.withRequiredArg().withValuesConvertedBy(IntegerValueConverter.NON_NEGATIVE).describedAs("int");
OptionSpec<Integer> optWarmupForks = parser.accepts("wf", "How many warmup forks to make for a single benchmark. " +
"All iterations within the warmup fork are not counted towards the benchmark score. Use 0 to disable " +
"warmup forks. " +
"(default: " + Defaults.WARMUP_FORKS + ")")
.withRequiredArg().withValuesConvertedBy(IntegerValueConverter.NON_NEGATIVE).describedAs("int");
OptionSpec<String> optOutput = parser.accepts("o", "Redirect human-readable output to a given file.")
.withRequiredArg().ofType(String.class).describedAs("filename");
OptionSpec<String> optOutputResults = parser.accepts("rff", "Write machine-readable results to a given file. " +
"The file format is controlled by -rf option. Please see the list of result formats for available " +
"formats. " +
"(default: " + Defaults.RESULT_FILE_PREFIX + ".<result-format>)")
.withRequiredArg().ofType(String.class).describedAs("filename");
OptionSpec<String> optProfilers = parser.accepts("prof", "Use profilers to collect additional benchmark data. " +
"Some profilers are not available on all JVMs and/or all OSes. Please see the list of available " +
"profilers with -lprof.")
.withRequiredArg().ofType(String.class).describedAs("profiler");
OptionSpec<Integer> optThreadGroups = parser.accepts("tg", "Override thread group distribution for asymmetric " +
"benchmarks. This option expects a comma-separated list of thread counts within the group. See " +
"@Group/@GroupThreads Javadoc for more information.")
.withRequiredArg().withValuesSeparatedBy(',').ofType(Integer.class)
.withValuesConvertedBy(IntegerValueConverter.NON_NEGATIVE).describedAs("int+");
OptionSpec<String> optJvm = parser.accepts("jvm", "Use given JVM for runs. This option only affects forked runs.")
.withRequiredArg().ofType(String.class).describedAs("string");
OptionSpec<String> optJvmArgs = parser.accepts("jvmArgs", "Use given JVM arguments. Most options are inherited " +
"from the host VM options, but in some cases you want to pass the options only to a forked VM. Either " +
"single space-separated option line, or multiple options are accepted. This option only affects forked " +
"runs.")
.withRequiredArg().ofType(String.class).describedAs("string");
OptionSpec<String> optJvmArgsAppend = parser.accepts("jvmArgsAppend", "Same as jvmArgs, but append these " +
"options after the already given JVM args.")
.withRequiredArg().ofType(String.class).describedAs("string");
OptionSpec<String> optJvmArgsPrepend = parser.accepts("jvmArgsPrepend", "Same as jvmArgs, but prepend these " +
"options before the already given JVM arg.")
.withRequiredArg().ofType(String.class).describedAs("string");
OptionSpec<String> optTU = parser.accepts("tu", "Override time unit in benchmark results. Available time units " +
"are: [m, s, ms, us, ns]. " +
"(default: " + Defaults.OUTPUT_TIMEUNIT + ")")
.withRequiredArg().ofType(String.class).describedAs("TU");
OptionSpec<Integer> optOPI = parser.accepts("opi", "Override operations per invocation, see " +
"@OperationsPerInvocation Javadoc for details. " +
"(default: " + Defaults.OPS_PER_INVOCATION + ")")
.withRequiredArg().withValuesConvertedBy(IntegerValueConverter.POSITIVE).describedAs("int");
OptionSpec<String> optResultFormat = parser.accepts("rf", "Format type for machine-readable results. These " +
"results are written to a separate file (see -rff). See the list of available result formats with -lrf. " +
"(default: " + Defaults.RESULT_FORMAT +")")
.withRequiredArg().ofType(String.class).describedAs("type");
OptionSpec<String> optWarmupMode = parser.accepts("wm", "Warmup mode for warming up selected benchmarks. " +
"Warmup modes are: " + warmupModesDesc() +
"(default: " + Defaults.WARMUP_MODE + ")")
.withRequiredArg().ofType(String.class).describedAs("mode");
OptionSpec<String> optExcludes = parser.accepts("e", "Benchmarks to exclude from the run.")
.withRequiredArg().withValuesSeparatedBy(',').ofType(String.class).describedAs("regexp+");
OptionSpec<String> optParams = parser.accepts("p", "Benchmark parameters. This option is expected to be used " +
"once per parameter. Parameter name and parameter values should be separated with equals sign. " +
"Parameter values should be separated with commas.")
.withRequiredArg().ofType(String.class).describedAs("param={v,}*");
OptionSpec<String> optWarmupBenchmarks = parser.accepts("wmb", "Warmup benchmarks to include in the run in " +
"addition to already selected by the primary filters. Harness will not measure these benchmarks, but " +
"only use them for the warmup.")
.withRequiredArg().withValuesSeparatedBy(',').ofType(String.class).describedAs("regexp+");
parser.accepts("l", "List the benchmarks that match a filter, and exit.");
parser.accepts("lp", "List the benchmarks that match a filter, along with parameters, and exit.");
parser.accepts("lrf", "List machine-readable result formats, and exit.");
parser.accepts("lprof", "List profilers, and exit.");
parser.accepts("h", "Display help, and exit.");
try {
OptionSet set = parser.parse(argv);
if (set.has(optExcludes)) {
excludes.addAll(optExcludes.values(set));
}
if (set.has(optWarmupBenchmarks)) {
warmupMicros.addAll(optWarmupBenchmarks.values(set));
}
if (set.has(optTU)) {
String va = optTU.value(set);
TimeUnit tu;
if (va.equalsIgnoreCase("ns")) {
tu = TimeUnit.NANOSECONDS;
} else if (va.equalsIgnoreCase("us")) {
tu = TimeUnit.MICROSECONDS;
} else if (va.equalsIgnoreCase("ms")) {
tu = TimeUnit.MILLISECONDS;
} else if (va.equalsIgnoreCase("s")) {
tu = TimeUnit.SECONDS;
} else if (va.equalsIgnoreCase("m")) {
tu = TimeUnit.MINUTES;
} else if (va.equalsIgnoreCase("h")) {
tu = TimeUnit.HOURS;
} else {
throw new CommandLineOptionException("Unknown time unit: " + va);
}
timeUnit = Optional.of(tu);
} else {
timeUnit = Optional.none();
}
opsPerInvocation = toOptional(optOPI, set);
if (set.has(optWarmupMode)) {
try {
warmupMode = Optional.of(WarmupMode.valueOf(optWarmupMode.value(set)));
} catch (IllegalArgumentException iae) {
throw new CommandLineOptionException(iae.getMessage(), iae);
}
} else {
warmupMode = Optional.none();
}
if (set.has(optResultFormat)) {
try {
resultFormat = Optional.of(ResultFormatType.valueOf(optResultFormat.value(set).toUpperCase()));
} catch (IllegalArgumentException iae) {
throw new CommandLineOptionException(iae.getMessage(), iae);
}
} else {
resultFormat = Optional.none();
}
help = set.has("h");
list = set.has("l");
listWithParams = set.has("lp");
listResultFormats = set.has("lrf");
listProfilers = set.has("lprof");
iterations = toOptional(optMeasureCount, set);
batchSize = toOptional(optMeasureBatchSize, set);
runTime = toOptional(optMeasureTime, set);
warmupIterations = toOptional(optWarmupCount, set);
warmupBatchSize = toOptional(optWarmupBatchSize, set);
warmupTime = toOptional(optWarmupTime, set);
timeout = toOptional(optTimeoutTime, set);
threads = toOptional(optThreads, set);
synchIterations = toOptional(optSyncIters, set);
gcEachIteration = toOptional(optGC, set);
failOnError = toOptional(optFOE, set);
fork = toOptional(optForks, set);
warmupFork = toOptional(optWarmupForks, set);
output = toOptional(optOutput, set);
result = toOptional(optOutputResults, set);
if (set.has(optBenchmarkMode)) {
try {
List<Mode> modes = new ArrayList<>();
for (String m : optBenchmarkMode.values(set)) {
modes.add(Mode.deepValueOf(m));
}
benchMode.addAll(modes);
} catch (IllegalArgumentException iae) {
throw new CommandLineOptionException(iae.getMessage(), iae);
}
}
if (set.has(optVerboseMode)) {
try {
if (set.hasArgument(optVerboseMode)) {
verbose = Optional.of(VerboseMode.valueOf(set.valueOf(optVerboseMode).toUpperCase()));
} else {
verbose = Optional.of(VerboseMode.EXTRA);
}
} catch (IllegalArgumentException iae) {
throw new CommandLineOptionException(iae.getMessage(), iae);
}
} else {
verbose = Optional.none();
}
regexps.addAll(set.valuesOf(optArgs));
if (set.has(optProfilers)) {
try {
for (String m : optProfilers.values(set)) {
int idx = m.indexOf(":");
String profName = (idx == -1) ? m : m.substring(0, idx);
String params = (idx == -1) ? "" : m.substring(idx + 1);
profilers.add(new ProfilerConfig(profName, params));
}
} catch (IllegalArgumentException iae) {
throw new CommandLineOptionException(iae.getMessage(), iae);
}
}
if (set.has(optThreadGroups)) {
threadGroups.addAll(set.valuesOf(optThreadGroups));
int total = 0;
for (int group : threadGroups) {
total += group;
}
if (total <= 0) {
throw new CommandLineOptionException("Group thread count should be positive, but it is " + total);
}
}
jvm = toOptional(optJvm, set);
jvmArgs = treatQuoted(set, optJvmArgs);
jvmArgsAppend = treatQuoted(set, optJvmArgsAppend);
jvmArgsPrepend = treatQuoted(set, optJvmArgsPrepend);
if (set.hasArgument(optParams)) {
for (String p : optParams.values(set)) {
String[] keys = p.split("=", 2);
if (keys.length != 2) {
throw new CommandLineOptionException("Unable to parse parameter string \"" + p + "\"");
}
params.putAll(keys[0], Arrays.asList(keys[1].split(",")));
}
}
} catch (OptionException e) {
String message = e.getMessage();
Throwable cause = e.getCause();
if (cause instanceof ValueConversionException) {
message += ". " + cause.getMessage();
}
throw new CommandLineOptionException(message, e);
}
}
private String warmupModesDesc() {
StringBuilder sb = new StringBuilder();
for (WarmupMode mode : WarmupMode.values()) {
sb.append(mode);
sb.append(" = ");
switch (mode) {
case BULK:
sb.append("Warmup all benchmarks first, then do all the measurements. ");
break;
case INDI:
sb.append("Warmup each benchmark individually, then measure it. ");
break;
case BULK_INDI:
sb.append("Warmup all benchmarks first, then re-warmup each benchmark individually, then measure it. ");
break;
}
}
return sb.toString();
}
private static <T> Optional<T> toOptional(OptionSpec<T> option, OptionSet set) {
if (set.has(option)) {
return Optional.eitherOf(option.value(set));
}
return Optional.none();
}
public Optional<Collection<String>> treatQuoted(OptionSet set, OptionSpec<String> spec) {
if (set.hasArgument(spec)) {
try {
List<String> vals = spec.values(set);
if (vals.size() != 1) {
return Optional.<Collection<String>>of(vals);
} else {
// Windows launcher somehow ends up here, fall-through to single value treatment
}
} catch (OptionException e) {
// only a single value, fall through
}
return Optional.of(Utils.splitQuotedEscape(spec.value(set)));
}
return Optional.none();
}
public void showHelp() throws IOException {
parser.printHelpOn(System.out);
}
public void listProfilers() {
ProfilerFactory.listProfilers(System.out);
}
public void listResultFormats() {
StringBuilder sb = new StringBuilder();
for (ResultFormatType f : ResultFormatType.values()) {
sb.append(f.toString().toLowerCase());
sb.append(", ");
}
sb.setLength(sb.length() - 2);
System.out.println("Available formats: " + sb.toString());
}
public boolean shouldList() {
return list;
}
public boolean shouldListWithParams() {
return listWithParams;
}
public boolean shouldListResultFormats() {
return listResultFormats;
}
public boolean shouldHelp() {
return help;
}
public boolean shouldListProfilers() {
return listProfilers;
}
@Override
public Optional<WarmupMode> getWarmupMode() {
return warmupMode;
}
@Override
public List<String> getIncludes() {
return regexps;
}
@Override
public List<String> getExcludes() {
return excludes;
}
@Override
public List<String> getWarmupIncludes() {
return warmupMicros;
}
@Override
public Optional<String> getJvm() {
return jvm;
}
@Override
public Optional<Collection<String>> getJvmArgs() {
return jvmArgs;
}
@Override
public Optional<Collection<String>> getJvmArgsAppend() {
return jvmArgsAppend;
}
@Override
public Optional<Collection<String>> getJvmArgsPrepend() {
return jvmArgsPrepend;
}
@Override
public Optional<Collection<String>> getParameter(String name) {
Collection<String> list = params.get(name);
if (list == null || list.isEmpty()){
return Optional.none();
} else {
return Optional.of(list);
}
}
@Override
public Optional<Integer> getForkCount() {
return fork;
}
@Override
public Optional<Integer> getWarmupForkCount() {
return warmupFork;
}
@Override
public Optional<String> getOutput() {
return output;
}
@Override
public Optional<ResultFormatType> getResultFormat() {
return resultFormat;
}
@Override
public Optional<String> getResult() {
return result;
}
@Override
public Optional<Integer> getMeasurementIterations() {
return iterations;
}
@Override
public Optional<Integer> getMeasurementBatchSize() {
return batchSize;
}
@Override
public Optional<TimeValue> getMeasurementTime() {
return runTime;
}
@Override
public Optional<TimeValue> getWarmupTime() {
return warmupTime;
}
@Override
public Optional<Integer> getWarmupIterations() {
return warmupIterations;
}
@Override
public Optional<Integer> getWarmupBatchSize() {
return warmupBatchSize;
}
@Override
public Optional<Integer> getThreads() {
return threads;
}
@Override
public Optional<int[]> getThreadGroups() {
if (threadGroups.isEmpty()) {
return Optional.none();
} else {
int[] r = new int[threadGroups.size()];
for (int c = 0; c < r.length; c++) {
r[c] = threadGroups.get(c);
}
return Optional.of(r);
}
}
@Override
public Optional<Boolean> shouldDoGC() {
return gcEachIteration;
}
@Override
public Optional<Boolean> shouldSyncIterations() {
return synchIterations;
}
@Override
public Optional<VerboseMode> verbosity() {
return verbose;
}
@Override
public Optional<TimeUnit> getTimeUnit() {
return timeUnit;
}
@Override
public Optional<Integer> getOperationsPerInvocation() {
return opsPerInvocation;
}
@Override
public Optional<Boolean> shouldFailOnError() {
return failOnError;
}
@Override
public List<ProfilerConfig> getProfilers() {
return profilers;
}
@Override
public Collection<Mode> getBenchModes() {
return new HashSet<>(benchMode);
}
@Override
public Optional<TimeValue> getTimeout() {
return timeout;
}
}
| 28,311 | 41.638554 | 152 | java |
jmh | jmh-master/jmh-core/src/main/java/org/openjdk/jmh/runner/options/IntegerValueConverter.java | /*
* Copyright (c) 2014, 2015, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package org.openjdk.jmh.runner.options;
import joptsimple.ValueConversionException;
import joptsimple.ValueConverter;
import joptsimple.internal.Reflection;
/**
* Converts option value from {@link String} to {@link Integer} and makes sure the value exceeds given minimal threshold.
*/
public class IntegerValueConverter implements ValueConverter<Integer> {
private final static ValueConverter<Integer> TO_INT_CONVERTER = Reflection.findConverter(int.class);
public final static IntegerValueConverter POSITIVE = new IntegerValueConverter(1);
public final static IntegerValueConverter NON_NEGATIVE = new IntegerValueConverter(0);
private final int minValue;
public IntegerValueConverter(int minValue) {
this.minValue = minValue;
}
@Override
public Integer convert(String value) {
Integer newValue = TO_INT_CONVERTER.convert(value);
if (newValue == null) {
// should not get here
throw new ValueConversionException("value should not be null");
}
if (newValue < minValue) {
String message = "The given value " + value + " should be ";
if (minValue == 0) {
message += "non-negative";
} else if (minValue == 1) {
message += "positive";
} else {
message += "greater or equal than " + minValue;
}
throw new ValueConversionException(message);
}
return newValue;
}
@Override
public Class<? extends Integer> valueType() {
return TO_INT_CONVERTER.valueType();
}
@Override
public String valuePattern() {
return "int";
}
}
| 2,909 | 36.307692 | 121 | java |
jmh | jmh-master/jmh-core/src/main/java/org/openjdk/jmh/runner/options/OptionFormatter.java | /*
* Copyright (c) 2005, 2014, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package org.openjdk.jmh.runner.options;
import joptsimple.HelpFormatter;
import joptsimple.OptionDescriptor;
import org.openjdk.jmh.util.Utils;
import java.util.List;
import java.util.Map;
public class OptionFormatter implements HelpFormatter {
private static final String LINE_SEPARATOR = System.getProperty("line.separator");
public String format(Map<String, ? extends OptionDescriptor> options) {
StringBuilder sb = new StringBuilder();
sb.append("Usage: java -jar ... [regexp*] [options]");
sb.append("\n");
sb.append(" [opt] means optional argument.\n");
sb.append(" <opt> means required argument.\n");
sb.append(" \"+\" means comma-separated list of values.\n");
sb.append(" \"time\" arguments accept time suffixes, like \"100ms\".\n");
sb.append("\n");
sb.append("Command line options usually take precedence over annotations.");
sb.append("\n");
sb.append("\n");
for (OptionDescriptor each : options.values()) {
sb.append(lineFor(each));
}
return sb.toString();
}
private String lineFor(OptionDescriptor d) {
StringBuilder line = new StringBuilder();
StringBuilder o = new StringBuilder();
o.append(" ");
for (String str : d.options()) {
if (!d.representsNonOptions()) {
o.append("-");
}
o.append(str);
if (d.acceptsArguments()) {
o.append(" ");
if (d.requiresArgument()) {
o.append("<");
} else {
o.append("[");
}
o.append(d.argumentDescription());
if (d.requiresArgument()) {
o.append(">");
} else {
o.append("]");
}
}
}
final int optWidth = 30;
line.append(String.format("%-" + optWidth + "s", o.toString()));
boolean first = true;
String desc = d.description();
List<?> defaults = d.defaultValues();
if (defaults != null && !defaults.isEmpty()) {
desc += " (default: " + defaults.toString() + ")";
}
for (String l : Utils.rewrap(desc)) {
if (first) {
first = false;
} else {
line.append(LINE_SEPARATOR);
line.append(String.format("%-" + optWidth + "s", ""));
}
line.append(l);
}
line.append(LINE_SEPARATOR);
line.append(LINE_SEPARATOR);
return line.toString();
}
}
| 3,875 | 34.888889 | 86 | java |
jmh | jmh-master/jmh-core/src/main/java/org/openjdk/jmh/runner/options/Options.java | /*
* Copyright (c) 2005, 2013, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package org.openjdk.jmh.runner.options;
import org.openjdk.jmh.annotations.Mode;
import org.openjdk.jmh.results.format.ResultFormatType;
import org.openjdk.jmh.util.Optional;
import java.io.Serializable;
import java.util.Collection;
import java.util.List;
import java.util.concurrent.TimeUnit;
public interface Options extends Serializable {
/**
* Which benchmarks to execute?
* @return list of regexps matching the requested benchmarks
*/
List<String> getIncludes();
/**
* Which benchmarks to omit?
* @return list of regexps matching the ignored benchmarks
*/
List<String> getExcludes();
/**
* Which file to use for dumping the output
* @return file name
*/
Optional<String> getOutput();
/**
* Result format to use
* @return format type
*/
Optional<ResultFormatType> getResultFormat();
/**
* Which file to use for dumping the result
* @return file name
*/
Optional<String> getResult();
/**
* Should force GC between iterations?
* @return should GC?
*/
Optional<Boolean> shouldDoGC();
/**
* Profilers to use for the run.
* Profilers will start in the order specified by collection, and will stop in the reverse order.
* @return profilers to use; empty collection if no profilers are required
*/
List<ProfilerConfig> getProfilers();
/**
* How verbose should we be?
* @return verbosity mode
*/
Optional<VerboseMode> verbosity();
/**
* Should harness terminate on first error encountered?
* @return should terminate?
*/
Optional<Boolean> shouldFailOnError();
/**
* Number of threads to run
* @return number of threads; 0 to use maximum number of threads
* @see org.openjdk.jmh.annotations.Threads
*/
Optional<Integer> getThreads();
/**
* Thread subgroups distribution.
* @return array of thread ratios
* @see org.openjdk.jmh.annotations.Group
* @see org.openjdk.jmh.annotations.GroupThreads
*/
Optional<int[]> getThreadGroups();
/**
* Should synchronize iterations?
* @return should we?
*/
Optional<Boolean> shouldSyncIterations();
/**
* Number of warmup iterations
* @return number of warmup iterations
* @see org.openjdk.jmh.annotations.Warmup
*/
Optional<Integer> getWarmupIterations();
/**
* The duration for warmup iterations
* @return duration
* @see org.openjdk.jmh.annotations.Warmup
*/
Optional<TimeValue> getWarmupTime();
/**
* Number of batch size for warmup
* @return number of batch size for warmup
* @see org.openjdk.jmh.annotations.Warmup
*/
Optional<Integer> getWarmupBatchSize();
/**
* Warmup mode.
* @return warmup mode
* @see org.openjdk.jmh.runner.options.WarmupMode
*/
Optional<WarmupMode> getWarmupMode();
/**
* Which benchmarks to warmup before doing the run.
* @return list of regexps matching the relevant benchmarks; empty if no benchmarks are defined
*/
List<String> getWarmupIncludes();
/**
* Number of measurement iterations
* @return number of measurement iterations
* @see org.openjdk.jmh.annotations.Measurement
*/
Optional<Integer> getMeasurementIterations();
/**
* The duration for measurement iterations
* @return duration
* @see org.openjdk.jmh.annotations.Measurement
*/
Optional<TimeValue> getMeasurementTime();
/**
* Number of batch size for measurement
* @return number of batch size for measurement
* @see org.openjdk.jmh.annotations.Measurement
*/
Optional<Integer> getMeasurementBatchSize();
/**
* Benchmarks modes to execute.
* @return modes to execute the benchmarks in; empty to use the default modes
* @see org.openjdk.jmh.annotations.BenchmarkMode
*/
Collection<Mode> getBenchModes();
/**
* Timeunit to use in units.
* @return timeunit
* @see org.openjdk.jmh.annotations.OutputTimeUnit
*/
Optional<TimeUnit> getTimeUnit();
/**
* Operations per invocation.
* @return operations per invocation.
* @see org.openjdk.jmh.annotations.OperationsPerInvocation
*/
Optional<Integer> getOperationsPerInvocation();
/**
* Fork count
* @return fork count; 0, to prohibit forking
* @see org.openjdk.jmh.annotations.Fork
*/
Optional<Integer> getForkCount();
/**
* Number of initial forks to ignore the results for
* @return initial fork count; 0, to disable
* @see org.openjdk.jmh.annotations.Fork
*/
Optional<Integer> getWarmupForkCount();
/**
* JVM executable to use for forks
* @return path to JVM executable
*/
Optional<String> getJvm();
/**
* JVM parameters to use with forks
* @return JVM parameters
* @see org.openjdk.jmh.annotations.Fork
*/
Optional<Collection<String>> getJvmArgs();
/**
* JVM parameters to use with forks (these options will be appended
* after any other JVM option)
* @return JVM parameters
* @see org.openjdk.jmh.annotations.Fork
*/
Optional<Collection<String>> getJvmArgsAppend();
/**
* JVM parameters to use with forks (these options will be prepended
* before any other JVM option)
* @return JVM parameters
* @see org.openjdk.jmh.annotations.Fork
*/
Optional<Collection<String>> getJvmArgsPrepend();
/**
* The overridden value of the parameter.
* @param name parameter name
* @return parameter
* @see org.openjdk.jmh.annotations.Param
*/
Optional<Collection<String>> getParameter(String name);
/**
* Timeout: how long to wait for an iteration to complete.
* @return duration
*/
Optional<TimeValue> getTimeout();
}
| 7,150 | 27.834677 | 101 | java |
jmh | jmh-master/jmh-core/src/main/java/org/openjdk/jmh/runner/options/OptionsBuilder.java | /*
* Copyright (c) 2005, 2013, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package org.openjdk.jmh.runner.options;
import org.openjdk.jmh.annotations.Mode;
import org.openjdk.jmh.annotations.Threads;
import org.openjdk.jmh.profile.Profiler;
import org.openjdk.jmh.results.format.ResultFormatType;
import org.openjdk.jmh.util.HashMultimap;
import org.openjdk.jmh.util.Multimap;
import org.openjdk.jmh.util.Optional;
import org.openjdk.jmh.util.Utils;
import java.lang.management.ManagementFactory;
import java.util.*;
import java.util.concurrent.TimeUnit;
public class OptionsBuilder implements Options, ChainedOptionsBuilder {
private static final long serialVersionUID = -4088596253924343849L;
@Override
public Options build() {
return this;
}
// ---------------------------------------------------------------------------
private Options otherOptions;
@Override
public ChainedOptionsBuilder parent(Options other) {
this.otherOptions = other;
return this;
}
private static void checkGreaterOrEqual(int value, int minValue, String s) {
if (value >= minValue) {
return;
}
String message = s + " (" + value + ") should be ";
if (minValue == 0) {
message += "non-negative";
} else if (minValue == 1) {
message += "positive";
} else {
message += "greater or equal than " + minValue;
}
throw new IllegalArgumentException(message);
}
// ---------------------------------------------------------------------------
private final List<String> regexps = new ArrayList<>();
@Override
public ChainedOptionsBuilder include(String regexp) {
regexps.add(regexp);
return this;
}
@Override
public List<String> getIncludes() {
List<String> result = new ArrayList<>();
result.addAll(regexps);
if (otherOptions != null) {
result.addAll(otherOptions.getIncludes());
}
return result;
}
// ---------------------------------------------------------------------------
private final List<String> excludes = new ArrayList<>();
@Override
public ChainedOptionsBuilder exclude(String regexp) {
excludes.add(regexp);
return this;
}
@Override
public List<String> getExcludes() {
List<String> result = new ArrayList<>();
result.addAll(excludes);
if (otherOptions != null) {
result.addAll(otherOptions.getExcludes());
}
return result;
}
// ---------------------------------------------------------------------------
private Optional<String> output = Optional.none();
@Override
public ChainedOptionsBuilder output(String filename) {
this.output = Optional.of(filename);
return this;
}
@Override
public Optional<String> getOutput() {
if (otherOptions != null) {
return output.orAnother(otherOptions.getOutput());
} else {
return output;
}
}
// ---------------------------------------------------------------------------
private Optional<ResultFormatType> rfType = Optional.none();
@Override
public ChainedOptionsBuilder resultFormat(ResultFormatType type) {
rfType = Optional.of(type);
return this;
}
@Override
public Optional<ResultFormatType> getResultFormat() {
if (otherOptions != null) {
return rfType.orAnother(otherOptions.getResultFormat());
} else {
return rfType;
}
}
// ---------------------------------------------------------------------------
private Optional<String> result = Optional.none();
@Override
public ChainedOptionsBuilder result(String filename) {
this.result = Optional.of(filename);
return this;
}
@Override
public Optional<String> getResult() {
if (otherOptions != null) {
return result.orAnother(otherOptions.getResult());
} else {
return result;
}
}
// ---------------------------------------------------------------------------
private Optional<Boolean> shouldDoGC = Optional.none();
@Override
public ChainedOptionsBuilder shouldDoGC(boolean value) {
shouldDoGC = Optional.of(value);
return this;
}
@Override
public Optional<Boolean> shouldDoGC() {
if (otherOptions != null) {
return shouldDoGC.orAnother(otherOptions.shouldDoGC());
} else {
return shouldDoGC;
}
}
// ---------------------------------------------------------------------------
private final List<ProfilerConfig> profilers = new ArrayList<>();
@Override
public ChainedOptionsBuilder addProfiler(Class<? extends Profiler> prof) {
this.profilers.add(new ProfilerConfig(prof.getCanonicalName()));
return this;
}
@Override
public ChainedOptionsBuilder addProfiler(Class<? extends Profiler> prof, String initLine) {
this.profilers.add(new ProfilerConfig(prof.getCanonicalName(), initLine));
return this;
}
@Override
public ChainedOptionsBuilder addProfiler(String prof) {
this.profilers.add(new ProfilerConfig(prof, ""));
return this;
}
@Override
public ChainedOptionsBuilder addProfiler(String prof, String initLine) {
this.profilers.add(new ProfilerConfig(prof, initLine));
return this;
}
@Override
public List<ProfilerConfig> getProfilers() {
List<ProfilerConfig> result = new ArrayList<>();
result.addAll(profilers);
if (otherOptions != null) {
result.addAll(otherOptions.getProfilers());
}
return result;
}
// ---------------------------------------------------------------------------
private Optional<VerboseMode> verbosity = Optional.none();
@Override
public ChainedOptionsBuilder verbosity(VerboseMode mode) {
verbosity = Optional.of(mode);
return this;
}
@Override
public Optional<VerboseMode> verbosity() {
if (otherOptions != null) {
return verbosity.orAnother(otherOptions.verbosity());
} else {
return verbosity;
}
}
// ---------------------------------------------------------------------------
private Optional<Boolean> shouldFailOnError = Optional.none();
@Override
public ChainedOptionsBuilder shouldFailOnError(boolean value) {
shouldFailOnError = Optional.of(value);
return this;
}
@Override
public Optional<Boolean> shouldFailOnError() {
if (otherOptions != null) {
return shouldFailOnError.orAnother(otherOptions.shouldFailOnError());
} else {
return shouldFailOnError;
}
}
// ---------------------------------------------------------------------------
private Optional<Integer> threads = Optional.none();
@Override
public ChainedOptionsBuilder threads(int count) {
if (count != Threads.MAX) {
checkGreaterOrEqual(count, 1, "Threads");
}
this.threads = Optional.of(count);
return this;
}
@Override
public Optional<Integer> getThreads() {
if (otherOptions != null) {
return threads.orAnother(otherOptions.getThreads());
} else {
return threads;
}
}
// ---------------------------------------------------------------------------
private Optional<int[]> threadGroups = Optional.none();
@Override
public ChainedOptionsBuilder threadGroups(int... groups) {
if (groups != null) {
for (int i = 0; i < groups.length; i++) {
checkGreaterOrEqual(groups[i], 0, "Group #" + i + " thread count");
}
checkGreaterOrEqual(Utils.sum(groups), 1, "Group thread count");
}
this.threadGroups = Optional.of((groups == null || groups.length != 0) ? groups : null);
return this;
}
@Override
public Optional<int[]> getThreadGroups() {
if (otherOptions != null) {
return threadGroups.orAnother(otherOptions.getThreadGroups());
} else {
return threadGroups;
}
}
// ---------------------------------------------------------------------------
private Optional<Boolean> syncIterations = Optional.none();
@Override
public ChainedOptionsBuilder syncIterations(boolean value) {
this.syncIterations = Optional.of(value);
return this;
}
@Override
public Optional<Boolean> shouldSyncIterations() {
if (otherOptions != null) {
return syncIterations.orAnother(otherOptions.shouldSyncIterations());
} else {
return syncIterations;
}
}
// ---------------------------------------------------------------------------
private Optional<Integer> warmupIterations = Optional.none();
@Override
public ChainedOptionsBuilder warmupIterations(int value) {
checkGreaterOrEqual(value, 0, "Warmup iterations");
this.warmupIterations = Optional.of(value);
return this;
}
@Override
public Optional<Integer> getWarmupIterations() {
if (otherOptions != null) {
return warmupIterations.orAnother(otherOptions.getWarmupIterations());
} else {
return warmupIterations;
}
}
// ---------------------------------------------------------------------------
private Optional<Integer> warmupBatchSize = Optional.none();
@Override
public ChainedOptionsBuilder warmupBatchSize(int value) {
checkGreaterOrEqual(value, 1, "Warmup batch size");
this.warmupBatchSize = Optional.of(value);
return this;
}
@Override
public Optional<Integer> getWarmupBatchSize() {
if (otherOptions != null) {
return warmupBatchSize.orAnother(otherOptions.getWarmupBatchSize());
} else {
return warmupBatchSize;
}
}
// ---------------------------------------------------------------------------
private Optional<TimeValue> warmupTime = Optional.none();
@Override
public ChainedOptionsBuilder warmupTime(TimeValue value) {
this.warmupTime = Optional.of(value);
return this;
}
@Override
public Optional<TimeValue> getWarmupTime() {
if (otherOptions != null) {
return warmupTime.orAnother(otherOptions.getWarmupTime());
} else {
return warmupTime;
}
}
// ---------------------------------------------------------------------------
private Optional<WarmupMode> warmupMode = Optional.none();
@Override
public ChainedOptionsBuilder warmupMode(WarmupMode mode) {
this.warmupMode = Optional.of(mode);
return this;
}
@Override
public Optional<WarmupMode> getWarmupMode() {
if (otherOptions != null) {
return warmupMode.orAnother(otherOptions.getWarmupMode());
} else {
return warmupMode;
}
}
// ---------------------------------------------------------------------------
private final List<String> warmupMicros = new ArrayList<>();
@Override
public ChainedOptionsBuilder includeWarmup(String regexp) {
warmupMicros.add(regexp);
return this;
}
@Override
public List<String> getWarmupIncludes() {
List<String> result = new ArrayList<>();
result.addAll(warmupMicros);
if (otherOptions != null) {
result.addAll(otherOptions.getWarmupIncludes());
}
return result;
}
// ---------------------------------------------------------------------------
private Optional<Integer> iterations = Optional.none();
@Override
public ChainedOptionsBuilder measurementIterations(int count) {
checkGreaterOrEqual(count, 1, "Measurement iterations");
this.iterations = Optional.of(count);
return this;
}
@Override
public Optional<Integer> getMeasurementIterations() {
if (otherOptions != null) {
return iterations.orAnother(otherOptions.getMeasurementIterations());
} else {
return iterations;
}
}
// ---------------------------------------------------------------------------
private Optional<TimeValue> measurementTime = Optional.none();
@Override
public ChainedOptionsBuilder measurementTime(TimeValue value) {
this.measurementTime = Optional.of(value);
return this;
}
@Override
public Optional<TimeValue> getMeasurementTime() {
if (otherOptions != null) {
return measurementTime.orAnother(otherOptions.getMeasurementTime());
} else {
return measurementTime;
}
}
// ---------------------------------------------------------------------------
private Optional<Integer> measurementBatchSize = Optional.none();
@Override
public ChainedOptionsBuilder measurementBatchSize(int value) {
checkGreaterOrEqual(value, 1, "Measurement batch size");
this.measurementBatchSize = Optional.of(value);
return this;
}
@Override
public Optional<Integer> getMeasurementBatchSize() {
if (otherOptions != null) {
return measurementBatchSize.orAnother(otherOptions.getMeasurementBatchSize());
} else {
return measurementBatchSize;
}
}
// ---------------------------------------------------------------------------
private final EnumSet<Mode> benchModes = EnumSet.noneOf(Mode.class);
@Override
public ChainedOptionsBuilder mode(Mode mode) {
benchModes.add(mode);
return this;
}
@Override
public Collection<Mode> getBenchModes() {
if (otherOptions != null && benchModes.isEmpty()) {
return otherOptions.getBenchModes();
} else {
return benchModes;
}
}
// ---------------------------------------------------------------------------
private Optional<TimeUnit> timeUnit = Optional.none();
@Override
public ChainedOptionsBuilder timeUnit(TimeUnit tu) {
this.timeUnit = Optional.of(tu);
return this;
}
@Override
public Optional<TimeUnit> getTimeUnit() {
if (otherOptions != null) {
return timeUnit.orAnother(otherOptions.getTimeUnit());
} else {
return timeUnit;
}
}
// ---------------------------------------------------------------------------
private Optional<Integer> opsPerInvocation = Optional.none();
@Override
public ChainedOptionsBuilder operationsPerInvocation(int opsPerInv) {
checkGreaterOrEqual(opsPerInv, 1, "Operations per invocation");
this.opsPerInvocation = Optional.of(opsPerInv);
return this;
}
@Override
public Optional<Integer> getOperationsPerInvocation() {
if (otherOptions != null) {
return opsPerInvocation.orAnother(otherOptions.getOperationsPerInvocation());
} else {
return opsPerInvocation;
}
}
// ---------------------------------------------------------------------------
private Optional<Integer> forks = Optional.none();
@Override
public ChainedOptionsBuilder forks(int value) {
checkGreaterOrEqual(value, 0, "Forks");
this.forks = Optional.of(value);
return this;
}
@Override
public Optional<Integer> getForkCount() {
if (otherOptions != null) {
return forks.orAnother(otherOptions.getForkCount());
} else {
return forks;
}
}
// ---------------------------------------------------------------------------
private Optional<Integer> warmupForks = Optional.none();
@Override
public ChainedOptionsBuilder warmupForks(int value) {
checkGreaterOrEqual(value, 0, "Warmup forks");
this.warmupForks = Optional.of(value);
return this;
}
@Override
public Optional<Integer> getWarmupForkCount() {
if (otherOptions != null) {
return warmupForks.orAnother(otherOptions.getWarmupForkCount());
} else {
return warmupForks;
}
}
// ---------------------------------------------------------------------------
private Optional<String> jvmBinary = Optional.none();
@Override
public ChainedOptionsBuilder jvm(String path) {
this.jvmBinary = Optional.of(path);
return this;
}
@Override
public Optional<String> getJvm() {
if (otherOptions != null) {
return jvmBinary.orAnother(otherOptions.getJvm());
} else {
return jvmBinary;
}
}
// ---------------------------------------------------------------------------
private Optional<Collection<String>> jvmArgs = Optional.none();
@Override
public ChainedOptionsBuilder jvmArgs(String... value) {
jvmArgs = Optional.<Collection<String>>of(Arrays.asList(value));
return this;
}
@Override
public Optional<Collection<String>> getJvmArgs() {
if (otherOptions != null) {
return jvmArgs.orAnother(otherOptions.getJvmArgs());
} else {
return jvmArgs;
}
}
// ---------------------------------------------------------------------------
private Optional<Collection<String>> jvmArgsAppend = Optional.none();
@Override
public ChainedOptionsBuilder jvmArgsAppend(String... value) {
jvmArgsAppend = Optional.<Collection<String>>of(Arrays.asList(value));
return this;
}
@Override
public Optional<Collection<String>> getJvmArgsAppend() {
if (otherOptions != null) {
return jvmArgsAppend.orAnother(otherOptions.getJvmArgsAppend());
} else {
return jvmArgsAppend;
}
}
// ---------------------------------------------------------------------------
private Optional<Collection<String>> jvmArgsPrepend = Optional.none();
@Override
public ChainedOptionsBuilder jvmArgsPrepend(String... value) {
jvmArgsPrepend = Optional.<Collection<String>>of(Arrays.asList(value));
return this;
}
@Override
public Optional<Collection<String>> getJvmArgsPrepend() {
if (otherOptions != null) {
return jvmArgsPrepend.orAnother(otherOptions.getJvmArgsPrepend());
} else {
return jvmArgsPrepend;
}
}
// ---------------------------------------------------------------------------
@Override
public ChainedOptionsBuilder detectJvmArgs() {
List<String> inputArguments = ManagementFactory.getRuntimeMXBean().getInputArguments();
return jvmArgs(inputArguments.toArray(new String[0]));
}
// ---------------------------------------------------------------------------
private final Multimap<String, String> params = new HashMultimap<>();
@Override
public Optional<Collection<String>> getParameter(String name) {
Collection<String> list = params.get(name);
if (list == null || list.isEmpty()){
if (otherOptions != null) {
return otherOptions.getParameter(name);
} else {
return Optional.none();
}
} else {
return Optional.of(list);
}
}
@Override
public ChainedOptionsBuilder param(String name, String... values) {
params.putAll(name, Arrays.asList(values));
return this;
}
// ---------------------------------------------------------------------------
private Optional<TimeValue> timeout = Optional.none();
@Override
public ChainedOptionsBuilder timeout(TimeValue value) {
this.timeout = Optional.of(value);
return this;
}
@Override
public Optional<TimeValue> getTimeout() {
if (otherOptions != null) {
return timeout.orAnother(otherOptions.getTimeout());
} else {
return timeout;
}
}
// ---------------------------------------------------------------------------
}
| 21,587 | 28.941748 | 96 | java |
jmh | jmh-master/jmh-core/src/main/java/org/openjdk/jmh/runner/options/ProfilerConfig.java | /*
* Copyright (c) 2014, 2020, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package org.openjdk.jmh.runner.options;
import java.io.Serializable;
public class ProfilerConfig implements Serializable {
private static final long serialVersionUID = -5105358164257442449L;
private final String klass;
private final String opts;
public ProfilerConfig(String klass, String opts) {
this.klass = klass;
this.opts = opts;
}
public ProfilerConfig(String klass) {
this.klass = klass;
this.opts = "";
}
public String getKlass() {
return klass;
}
public String getOpts() {
return opts;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
ProfilerConfig that = (ProfilerConfig) o;
if (!klass.equals(that.klass)) return false;
if (!opts.equals(that.opts)) return false;
return true;
}
@Override
public int hashCode() {
int result = klass.hashCode();
result = 31 * result + opts.hashCode();
return result;
}
@Override
public String toString() {
return klass + ":" + opts;
}
}
| 2,398 | 29.367089 | 79 | java |
jmh | jmh-master/jmh-core/src/main/java/org/openjdk/jmh/runner/options/ThreadsValueConverter.java | /*
* Copyright (c) 2014, 2015, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package org.openjdk.jmh.runner.options;
import joptsimple.ValueConverter;
import org.openjdk.jmh.annotations.Threads;
/**
* Converts {@link String} value to {@link Integer} and uses {@link Threads#MAX} if {@code max} string was given.
*/
public class ThreadsValueConverter implements ValueConverter<Integer> {
public static final ValueConverter<Integer> INSTANCE = new ThreadsValueConverter();
@Override
public Integer convert(String value) {
if (value.equalsIgnoreCase("max")) {
return Threads.MAX;
}
return IntegerValueConverter.POSITIVE.convert(value);
}
@Override
public Class<? extends Integer> valueType() {
return IntegerValueConverter.POSITIVE.valueType();
}
@Override
public String valuePattern() {
return IntegerValueConverter.POSITIVE.valuePattern();
}
}
| 2,078 | 37.5 | 113 | java |
jmh | jmh-master/jmh-core/src/main/java/org/openjdk/jmh/runner/options/TimeValue.java | /*
* Copyright (c) 2005, 2013, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package org.openjdk.jmh.runner.options;
import java.io.Serializable;
import java.util.concurrent.TimeUnit;
/**
* A generic time scalar.
*/
public class TimeValue implements Serializable {
private static final long serialVersionUID = 1L;
public static final TimeValue NONE = new TimeValue(0, TimeUnit.SECONDS);
public static TimeValue days(long v) {
return new TimeValue(v, TimeUnit.DAYS);
}
public static TimeValue hours(long v) {
return new TimeValue(v, TimeUnit.HOURS);
}
public static TimeValue microseconds(long v) {
return new TimeValue(v, TimeUnit.MICROSECONDS);
}
public static TimeValue milliseconds(long v) {
return new TimeValue(v, TimeUnit.MILLISECONDS);
}
public static TimeValue minutes(long v) {
return new TimeValue(v, TimeUnit.MINUTES);
}
public static TimeValue nanoseconds(long v) {
return new TimeValue(v, TimeUnit.NANOSECONDS);
}
public static TimeValue seconds(long v) {
return new TimeValue(v, TimeUnit.SECONDS);
}
private final long time;
private final TimeUnit timeUnit;
public TimeValue(long time, TimeUnit timeUnit) {
if (time < 0) {
throw new IllegalArgumentException("Time should be greater or equal to zero: " + time);
}
this.time = time;
this.timeUnit = timeUnit;
}
public long getTime() {
return time;
}
public long convertTo(TimeUnit tu) {
return tu.convert(time, timeUnit);
}
public TimeUnit getTimeUnit() {
return timeUnit;
}
@Override
public int hashCode() {
int hash = 3;
hash = 41 * hash + (int) (this.time ^ (this.time >>> 32));
hash = 41 * hash + (this.timeUnit != null ? this.timeUnit.hashCode() : 0);
return hash;
}
@Override
public boolean equals(Object obj) {
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
final TimeValue other = (TimeValue) obj;
if (this.time != other.time) {
return false;
}
if (this.timeUnit != other.timeUnit) {
return false;
}
return true;
}
@Override
public String toString() {
if (time == 0) {
return "single-shot";
} else {
return time + " " + tuToString(timeUnit);
}
}
/**
* Converts timeunit to stringly representation.
*
* @param timeUnit timeunit to convert
* @return string representation
*/
public static String tuToString(TimeUnit timeUnit) {
switch (timeUnit) {
case DAYS:
return "day";
case HOURS:
return "hr";
case MICROSECONDS:
return "us";
case MILLISECONDS:
return "ms";
case MINUTES:
return "min";
case NANOSECONDS:
return "ns";
case SECONDS:
return "s";
default:
return "?";
}
}
/**
* Parses time value from a string representation.
* This method is called by joptsimple to resolve string values.
* @param timeString string representation of a time value
* @return TimeValue value
*/
public static TimeValue valueOf(String timeString) {
return fromString(timeString);
}
public static TimeValue fromString(String timeString) {
if (timeString == null) {
throw new IllegalArgumentException("String is null");
}
timeString = timeString.replaceAll(" ", "").toLowerCase();
if (timeString.contains("ns")) {
return new TimeValue(Integer.parseInt(timeString.substring(0, timeString.indexOf("ns"))), TimeUnit.NANOSECONDS);
}
if (timeString.contains("ms")) {
return new TimeValue(Integer.parseInt(timeString.substring(0, timeString.indexOf("ms"))), TimeUnit.MILLISECONDS);
}
if (timeString.contains("us")) {
return new TimeValue(Integer.parseInt(timeString.substring(0, timeString.indexOf("us"))), TimeUnit.MICROSECONDS);
}
if (timeString.contains("s")) {
return new TimeValue(Integer.parseInt(timeString.substring(0, timeString.indexOf("s"))), TimeUnit.SECONDS);
}
if (timeString.contains("m")) {
return new TimeValue(Integer.parseInt(timeString.substring(0, timeString.indexOf("m"))), TimeUnit.MINUTES);
}
if (timeString.contains("hr")) {
return new TimeValue(Integer.parseInt(timeString.substring(0, timeString.indexOf("hr"))), TimeUnit.HOURS);
}
if (timeString.contains("day")) {
return new TimeValue(Integer.parseInt(timeString.substring(0, timeString.indexOf("day"))), TimeUnit.DAYS);
}
return new TimeValue(Integer.parseInt(timeString), TimeUnit.SECONDS);
}
public void sleep() throws InterruptedException {
timeUnit.sleep(time);
}
}
| 6,352 | 31.248731 | 125 | java |
jmh | jmh-master/jmh-core/src/main/java/org/openjdk/jmh/runner/options/VerboseMode.java | /*
* Copyright (c) 2005, 2014, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package org.openjdk.jmh.runner.options;
public enum VerboseMode {
/**
* Be completely silent.
*/
SILENT(0),
/**
* Output normally.
*/
NORMAL(1),
/**
* Output extra info.
*/
EXTRA(2),
;
private final int level;
VerboseMode(int level) {
this.level = level;
}
public boolean equalsOrHigherThan(VerboseMode other) {
return level >= other.level;
}
}
| 1,661 | 28.157895 | 79 | java |
jmh | jmh-master/jmh-core/src/main/java/org/openjdk/jmh/runner/options/WarmupMode.java | /*
* Copyright (c) 2005, 2013, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package org.openjdk.jmh.runner.options;
/**
* Warmup Mode enum
*/
public enum WarmupMode {
/**
* Do the individual warmup for every benchmark
*/
INDI(false, true),
/**
* Do the bulk warmup before any benchmark starts.
*/
BULK(true, false),
/**
* Do the bulk warmup before any benchmark starts,
* and then also do individual warmups for every
* benchmark.
*/
BULK_INDI(true, true),
;
private final boolean bulk;
private final boolean indi;
WarmupMode(boolean bulk, boolean indi) {
this.bulk = bulk;
this.indi = indi;
}
public boolean isBulk() {
return bulk;
}
public boolean isIndi() {
return indi;
}
}
| 1,958 | 28.238806 | 79 | java |
jmh | jmh-master/jmh-core/src/main/java/org/openjdk/jmh/util/AbstractStatistics.java | /*
* Copyright (c) 2005, 2013, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package org.openjdk.jmh.util;
import org.apache.commons.math3.distribution.TDistribution;
import org.apache.commons.math3.stat.inference.TestUtils;
public abstract class AbstractStatistics implements Statistics {
private static final long serialVersionUID = 1536835581997509117L;
/**
* Returns the interval c1, c2 of which there's an 1-alpha
* probability of the mean being within the interval.
*
* @param confidence level
* @return the confidence interval
*/
@Override
public double[] getConfidenceIntervalAt(double confidence) {
double[] interval = new double[2];
if (getN() <= 2) {
interval[0] = interval[1] = Double.NaN;
return interval;
}
TDistribution tDist = new TDistribution(getN() - 1);
double a = tDist.inverseCumulativeProbability(1 - (1 - confidence) / 2);
interval[0] = getMean() - a * getStandardDeviation() / Math.sqrt(getN());
interval[1] = getMean() + a * getStandardDeviation() / Math.sqrt(getN());
return interval;
}
@Override
public boolean isDifferent(Statistics other, double confidence) {
return TestUtils.tTest(this, other, 1 - confidence);
}
@Override
public double getMeanErrorAt(double confidence) {
if (getN() <= 2) return Double.NaN;
TDistribution tDist = new TDistribution(getN() - 1);
double a = tDist.inverseCumulativeProbability(1 - (1 - confidence) / 2);
return a * getStandardDeviation() / Math.sqrt(getN());
}
@Override
public String toString() {
return "N:" + getN() + " Mean: " + getMean()
+ " Min: " + getMin() + " Max: " + getMax()
+ " StdDev: " + getStandardDeviation();
}
@Override
public double getMean() {
if (getN() > 0) {
return getSum() / getN();
} else {
return Double.NaN;
}
}
@Override
public double getStandardDeviation() {
return Math.sqrt(getVariance());
}
@Override
public int compareTo(Statistics other, double confidence) {
if (isDifferent(other, confidence)) {
return Double.compare(getMean(), other.getMean());
} else {
return 0;
}
}
@Override
public int compareTo(Statistics other) {
return compareTo(other, 0.99);
}
}
| 3,619 | 33.47619 | 81 | java |
jmh | jmh-master/jmh-core/src/main/java/org/openjdk/jmh/util/BoundedPriorityQueue.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 java.io.Serializable;
import java.util.*;
/**
* Bounded variant of {@link PriorityQueue}.
* Note: elements are returned in reverse order.
* For instance, if "top N smallest elements" are required, use {@code new BoundedPriorityQueue(N)},
* and the elements would be returned in largest to smallest order.
*
* @param <E> type of the element
*/
public class BoundedPriorityQueue<E> extends AbstractQueue<E> implements Serializable {
private static final long serialVersionUID = 7159618773497127413L;
private final int maxSize;
private final Comparator<? super E> comparator;
private final Queue<E> queue;
/**
* Creates a bounded priority queue with the specified maximum size and default ordering.
* At most {@code maxSize} smallest elements would be kept in the queue.
*
* @param maxSize maximum size of the queue
*/
public BoundedPriorityQueue(int maxSize) {
this(maxSize, null);
}
/**
* Creates a bounded priority queue with the specified maximum size.
* At most {@code maxSize} smallest elements would be kept in the queue.
*
* @param maxSize maximum size of the queue
* @param comparator comparator that orders the elements
*/
public BoundedPriorityQueue(int maxSize, Comparator<? super E> comparator) {
this.maxSize = maxSize;
this.comparator = reverse(comparator);
this.queue = new PriorityQueue<>(10, this.comparator);
}
/**
* Internal queue should be in fact in reverse order.
* By default, the queue aims for "top N smallest elements".
* So peek() should return the biggest element, so it can be removed when adding smaller element
*
* @param comparator comparator that designates ordering of the entries or {@code null} for default ordering
* @param <E> type of the element
* @return reverse comparator
*/
private static <E> Comparator<? super E> reverse(Comparator<? super E> comparator) {
if (comparator == null) {
return Collections.reverseOrder();
}
return Collections.reverseOrder(comparator);
}
@Override
public boolean add(E e) {
return offer(e);
}
@Override
public boolean offer(E e) {
if (queue.size() >= maxSize) {
E head = peek();
if (comparator.compare(e, head) < 1) {
return false;
}
poll();
}
return queue.offer(e);
}
@Override
public E poll() {
return queue.poll();
}
@Override
public E peek() {
return queue.peek();
}
@Override
public Iterator<E> iterator() {
return queue.iterator();
}
@Override
public int size() {
return queue.size();
}
}
| 4,061 | 32.570248 | 112 | java |
jmh | jmh-master/jmh-core/src/main/java/org/openjdk/jmh/util/ClassUtils.java | /*
* Copyright (c) 2005, 2013, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package org.openjdk.jmh.util;
import java.io.File;
import java.io.IOException;
import java.lang.reflect.Method;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLClassLoader;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* A utility class for loading classes in various ways.
*/
public class ClassUtils {
private static final boolean USE_SEPARATE_CLASSLOADER = Boolean.getBoolean("jmh.separateClassLoader");
// Static access only
private ClassUtils() {
}
/**
* Enumerates all methods in hierarchy. Note that is different from both Class.getDeclaredMethods() and
* Class.getMethods().
*
* @param clazz class to enumerate.
* @return list of methods.
*/
public static List<Method> enumerateMethods(Class<?> clazz) {
List<Method> result = new ArrayList<>();
Class<?> current = clazz;
while (current != null) {
result.addAll(Arrays.asList(current.getDeclaredMethods()));
current = current.getSuperclass();
}
return result;
}
public static Class<?> loadClass(String className) {
try {
if (!USE_SEPARATE_CLASSLOADER) {
return Class.forName(className);
}
// Load the class in a different classloader
String classPathValue = System.getProperty("java.class.path");
String[] classPath = classPathValue.split(File.pathSeparator);
URL[] classPathUrl = new URL[classPath.length];
for (int i = 0; i < classPathUrl.length; i++) {
try {
classPathUrl[i] = new File(classPath[i]).toURI().toURL();
} catch (MalformedURLException ex) {
throw new IllegalStateException("Error parsing the value of property java.class.path: " + classPathValue, ex);
}
}
try (URLClassLoader loader = new URLClassLoader(classPathUrl)) {
return loader.loadClass(className);
} catch (IOException e) {
throw new IllegalStateException(e);
}
} catch (ClassNotFoundException ex) {
throw new IllegalArgumentException("Benchmark does not match a class", ex);
}
}
/**
* Make the collection of class names denser.
*
* @param src source class names
* @return map of [src class name, denser class name]
*/
public static Map<String, String> denseClassNames(Collection<String> src) {
if (src.isEmpty()) return Collections.emptyMap();
int maxLen = Integer.MIN_VALUE;
for (String s : src) {
maxLen = Math.max(maxLen, s.length());
}
boolean first = true;
boolean prefixCut = false;
String[] prefix = new String[0];
for (String s : src) {
String[] names = s.split("\\.");
if (first) {
prefix = new String[names.length];
int c;
for (c = 0; c < names.length; c++) {
if (names[c].toLowerCase().equals(names[c])) {
prefix[c] = names[c];
} else {
break;
}
}
prefix = Arrays.copyOf(prefix, c);
first = false;
continue;
}
int c = 0;
while (c < Math.min(prefix.length, names.length)) {
String n = names[c];
String p = prefix[c];
if (!n.equals(p) || !n.toLowerCase().equals(n)) {
break;
}
c++;
}
if (prefix.length != c) {
prefixCut = true;
}
prefix = Arrays.copyOf(prefix, c);
}
for (int c = 0; c < prefix.length; c++) {
prefix[c] = prefixCut ? String.valueOf(prefix[c].charAt(0)) : "";
}
Map<String, String> result = new HashMap<>();
for (String s : src) {
int prefixLen = prefix.length;
String[] names = s.split("\\.");
System.arraycopy(prefix, 0, names, 0, prefixLen);
String dense = "";
for (String n : names) {
if (!n.isEmpty()) {
dense += n + ".";
}
}
if (dense.endsWith(".")) {
dense = dense.substring(0, dense.length() - 1);
}
result.put(s, dense);
}
return result;
}
}
| 5,956 | 31.730769 | 130 | java |
jmh | jmh-master/jmh-core/src/main/java/org/openjdk/jmh/util/CountingMap.java | /*
* Copyright (c) 2022, 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;
import java.util.HashMap;
import java.util.Map;
public class CountingMap<K> {
final Map<K, MutableInt> map = new HashMap<>();
public int incrementAndGet(K k) {
MutableInt mi = map.get(k);
if (mi == null) {
mi = new MutableInt();
map.put(k, mi);
}
return mi.incrementAndGet();
}
private static class MutableInt {
int value;
int incrementAndGet() {
return ++value;
}
}
}
| 1,708 | 32.509804 | 76 | java |
jmh | jmh-master/jmh-core/src/main/java/org/openjdk/jmh/util/Deduplicator.java | /*
* Copyright (c) 2014, 2014, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package org.openjdk.jmh.util;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
public class Deduplicator<T> {
final ConcurrentMap<T, T> map;
public Deduplicator() {
map = new ConcurrentHashMap<>();
}
public T dedup(T t) {
T et = map.putIfAbsent(t, t);
if (et != null) {
return et;
} else {
return t;
}
}
}
| 1,650 | 33.395833 | 79 | java |
jmh | jmh-master/jmh-core/src/main/java/org/openjdk/jmh/util/DelegatingMultimap.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 java.io.Serializable;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Map;
public class DelegatingMultimap<K, V> implements Multimap<K, V>, Serializable {
private static final long serialVersionUID = 7026540942232962263L;
protected final Map<K, Collection<V>> map;
public DelegatingMultimap(Map<K, Collection<V>> map) {
this.map = map;
}
protected Collection<V> createValueCollection() {
return new ArrayList<>();
}
@Override
public void put(K key, V value) {
Collection<V> vs = map.get(key);
if (vs == null) {
vs = createValueCollection();
map.put(key, vs);
}
vs.add(value);
}
@Override
public void putAll(K key, Collection<V> vvs) {
Collection<V> vs = map.get(key);
if (vs == null) {
vs = createValueCollection();
map.put(key, vs);
}
vs.addAll(vvs);
}
@Override
public Collection<V> get(K key) {
Collection<V> vs = map.get(key);
return (vs == null) ? Collections.<V>emptyList() : Collections.unmodifiableCollection(vs);
}
@Override
public boolean isEmpty() {
return map.isEmpty();
}
@Override
public void clear() {
map.clear();
}
@Override
public Collection<K> keys() {
return map.keySet();
}
@Override
public Collection<V> values() {
Collection<V> result = createValueCollection();
for (Collection<V> vs : map.values()) {
result.addAll(vs);
}
return result;
}
public Collection<Map.Entry<K, Collection<V>>> entrySet() {
return map.entrySet();
}
@Override
public void remove(K key) {
map.remove(key);
}
@Override
public void merge(Multimap<K, V> other) {
for (K k : other.keys()) {
putAll(k, other.get(k));
}
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
@SuppressWarnings("unchecked")
DelegatingMultimap<K, V> that = (DelegatingMultimap<K, V>) o;
if (!map.equals(that.map)) return false;
return true;
}
@Override
public int hashCode() {
return map.hashCode();
}
@Override
public String toString() {
return map.toString();
}
}
| 3,739 | 26.703704 | 98 | java |
jmh | jmh-master/jmh-core/src/main/java/org/openjdk/jmh/util/DelegatingMultiset.java | /*
* Copyright (c) 2014, 2022, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package org.openjdk.jmh.util;
import java.io.Serializable;
import java.util.Collection;
import java.util.Collections;
import java.util.Map;
public class DelegatingMultiset<T> implements Multiset<T>, Serializable {
private static final long serialVersionUID = -8454789908011859615L;
protected final Map<T, Long> map;
private long size;
public DelegatingMultiset(Map<T, Long> map) {
this.map = map;
}
@Override
public void add(T element) {
add(element, 1);
}
@Override
public void add(T element, long add) {
Long count = map.get(element);
if (count == null) {
count = 0L;
}
count += add;
size += add;
if (count != 0) {
map.put(element, count);
} else {
map.remove(element);
}
}
@Override
public long count(T element) {
Long count = map.get(element);
return (count == null) ? 0 : count;
}
@Override
public Collection<Map.Entry<T, Long>> entrySet() {
return map.entrySet();
}
@Override
public boolean isEmpty() {
return map.isEmpty();
}
@Override
public long size() {
return size;
}
@Override
public Collection<T> keys() {
return Collections.unmodifiableCollection(map.keySet());
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
@SuppressWarnings("unchecked")
DelegatingMultiset<T> that = (DelegatingMultiset<T>) o;
if (size != that.size) return false;
if (!map.equals(that.map)) return false;
return true;
}
@Override
public int hashCode() {
int result = map.hashCode();
result = 31 * result + (int) (size ^ (size >>> 32));
return result;
}
@Override
public void clear() {
size = 0;
map.clear();
}
}
| 3,211 | 26.930435 | 79 | java |
jmh | jmh-master/jmh-core/src/main/java/org/openjdk/jmh/util/FileUtils.java | /*
* Copyright (c) 2005, 2013, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package org.openjdk.jmh.util;
import java.io.*;
import java.nio.file.Files;
import java.util.ArrayList;
import java.util.Collection;
import java.util.LinkedList;
import java.util.List;
/**
* A utility class for File creation and manipulation.
*/
public class FileUtils {
// Static access only
private FileUtils() {
}
static final TempFileManager TEMP_FILE_MANAGER = new TempFileManager();
/**
* Creates the temp file, and retains it as long as the reference to it
* is reachable.
*
* @param suffix suffix
* @return temp file
* @throws IOException if things go crazy
*/
public static TempFile weakTempFile(String suffix) throws IOException {
return TEMP_FILE_MANAGER.create(suffix);
}
public static void purgeTemps() {
TEMP_FILE_MANAGER.purge();
}
/**
* Creates the temp file with given suffix. The file would be removed
* on JVM exit, or when caller deletes the file itself.
*
* @param suffix suffix
* @return temporary file
* @throws IOException if things go crazy
*/
public static File tempFile(String suffix) throws IOException {
File file = File.createTempFile("jmh", suffix);
file.deleteOnExit();
return file;
}
/**
* Helper method for extracting a given resource to File
*
* @param name name of the resource
* @return a File pointing to the extracted resource
* @throws IOException if things go crazy
*/
public static File extractFromResource(String name) throws IOException {
File temp = FileUtils.tempFile("extracted");
try (InputStream fis = FileUtils.class.getResourceAsStream(name);
OutputStream fos = new FileOutputStream(temp)) {
byte[] buf = new byte[8192];
int read;
while ((read = fis.read(buf)) != -1) {
fos.write(buf, 0, read);
}
fos.close();
return temp;
}
}
/**
* Create a temporary file (see {@link File#createTempFile(String, String)}) and fill it with the given lines.
*
* @param suffix file suffix {@link File#createTempFile(String, String)}
* @param lines to be written
*
* @return the temporary file absolute path
* @throws IOException on file creation error
*/
public static String createTempFileWithLines(String suffix, Iterable<String> lines)
throws IOException {
File file = FileUtils.tempFile(suffix);
PrintWriter pw = new PrintWriter(file);
for (String l : lines) {
pw.println(l);
}
pw.close();
return file.getAbsolutePath();
}
public static Collection<String> tail(File file, int num) throws IOException {
try (FileInputStream fis = new FileInputStream(file);
InputStreamReader is = new InputStreamReader(fis);
BufferedReader reader = new BufferedReader(is)) {
LinkedList<String> lines = new LinkedList<>();
String line;
while ((line = reader.readLine()) != null) {
lines.add(line);
if (lines.size() > num) {
lines.remove(0);
}
}
return lines;
}
}
public static Collection<String> readAllLines(Reader src) throws IOException {
BufferedReader reader = new BufferedReader(src);
List<String> lines = new ArrayList<>();
String line;
while ((line = reader.readLine()) != null) {
lines.add(line);
}
return lines;
}
public static Collection<String> readAllLines(File file) throws IOException {
try (FileReader fr = new FileReader(file)) {
return readAllLines(fr);
}
}
public static Collection<String> readAllLines(InputStream stream) throws IOException {
try (InputStreamReader reader = new InputStreamReader(stream)) {
return readAllLines(reader);
} finally {
FileUtils.safelyClose(stream);
}
}
public static void writeLines(File file, Collection<String> lines) throws IOException {
try (PrintWriter pw = new PrintWriter(file)) {
for (String line : lines) {
pw.println(line);
}
}
}
public static void appendLines(File file, Collection<String> lines) throws IOException {
Collection<String> newLines = new ArrayList<>();
try {
newLines.addAll(readAllLines(file));
} catch (IOException e) {
// no file
}
newLines.addAll(lines);
writeLines(file, newLines);
}
public static Collection<File> getClasses(File root) {
Collection<File> result = new ArrayList<>();
List<File> newDirs = new ArrayList<>();
newDirs.add(root);
while (!newDirs.isEmpty()) {
List<File> add = new ArrayList<>();
for (File dir : newDirs) {
File[] files = dir.listFiles();
if (files != null) {
for (File f : files) {
if (f.isDirectory()) {
add.add(f);
} else {
if (f.getName().endsWith(".class")) {
result.add(f);
}
}
}
}
}
newDirs.clear();
newDirs = add;
}
return result;
}
public static void copy(String src, String dst) throws IOException {
try (FileInputStream fis = new FileInputStream(src);
FileOutputStream fos = new FileOutputStream(dst)) {
byte[] buf = new byte[8192];
int read;
while ((read = fis.read(buf)) != -1) {
fos.write(buf, 0, read);
}
}
}
public static <T extends Flushable & Closeable> void safelyClose(T obj) {
if (obj != null) {
try {
obj.flush();
} catch (IOException e) {
// ignore
}
try {
obj.close();
} catch (IOException e) {
// ignore
}
}
}
public static <T extends Closeable> void safelyClose(T obj) {
if (obj != null) {
try {
obj.close();
} catch (IOException e) {
// do nothing
}
}
}
public static void touch(String f) throws IOException {
File file = new File(f);
try {
if (file.createNewFile() || file.canWrite()) {
return;
}
} catch (IOException e) {
// fall-through
}
throw new IOException("The file is not writable: " + f);
}
}
| 8,174 | 31.058824 | 114 | java |
jmh | jmh-master/jmh-core/src/main/java/org/openjdk/jmh/util/HashMultimap.java | /*
* Copyright (c) 2005, 2013, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package org.openjdk.jmh.util;
import java.io.Serializable;
import java.util.Collection;
import java.util.HashMap;
public class HashMultimap<K, V> extends DelegatingMultimap<K, V> implements Serializable {
private static final long serialVersionUID = 2484428623123444998L;
public HashMultimap() {
super(new HashMap<>());
}
}
| 1,560 | 40.078947 | 90 | java |
jmh | jmh-master/jmh-core/src/main/java/org/openjdk/jmh/util/HashMultiset.java | /*
* Copyright (c) 2005, 2013, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package org.openjdk.jmh.util;
import java.io.Serializable;
import java.util.HashMap;
public class HashMultiset<T> extends DelegatingMultiset<T> implements Serializable {
private static final long serialVersionUID = 8149201968248505516L;
public HashMultiset() {
super(new HashMap<>());
}
}
| 1,525 | 40.243243 | 84 | java |
jmh | jmh-master/jmh-core/src/main/java/org/openjdk/jmh/util/HashsetMultimap.java | /*
* Copyright (c) 2005, 2013, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package org.openjdk.jmh.util;
import java.io.Serializable;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
public class HashsetMultimap<K, V> extends DelegatingMultimap<K, V> implements Serializable {
private static final long serialVersionUID = -4236100656731956836L;
public HashsetMultimap() {
super(new HashMap<>());
}
@Override
protected Collection<V> createValueCollection() {
return new HashSet<>();
}
}
| 1,700 | 37.659091 | 93 | java |
jmh | jmh-master/jmh-core/src/main/java/org/openjdk/jmh/util/InputStreamDrainer.java | /*
* Copyright (c) 2005, 2013, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package org.openjdk.jmh.util;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
* Will drain the output stream.
*/
public final class InputStreamDrainer extends Thread {
private static final int BUF_SIZE = 1024;
private final List<OutputStream> outs;
private final InputStream in;
/**
* Create a drainer which will discard the read lines.
*
* @param in The input stream to drain
*/
public InputStreamDrainer(InputStream in) {
this(in, null);
}
/**
* Create a drainer that will echo all read lines to <code>out</code>.
*
* @param in The input stream to drain
* @param out Where to drain the stream into
*/
public InputStreamDrainer(InputStream in, OutputStream out) {
this.in = in;
this.outs = new ArrayList<>();
addOutputStream(out);
}
/**
* Adds an output stream to drain the output to.
*
* @param out The output stream
*/
public void addOutputStream(OutputStream out) {
if (out != null) {
outs.add(out);
}
}
/** Drain the stream. */
public void run() {
byte[] buf = new byte[BUF_SIZE];
try {
int read;
while ((read = in.read(buf)) != -1) {
for (OutputStream out : outs) {
out.write(buf, 0, read);
}
}
for (OutputStream out : outs) {
out.flush();
}
} catch (IOException ioe) {
Logger.getLogger(this.getClass().getName()).log(Level.SEVERE, ioe.getMessage(), ioe);
} finally {
try {
in.close();
} catch (IOException ioe) {
Logger.getLogger(this.getClass().getName()).log(Level.SEVERE, ioe.getMessage(), ioe);
}
}
}
}
| 3,226 | 31.59596 | 101 | java |
jmh | jmh-master/jmh-core/src/main/java/org/openjdk/jmh/util/Interval.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;
public class Interval implements Comparable<Interval> {
public final long src;
public final long dst;
public Interval(long src, long dst) {
this.src = src;
this.dst = dst;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Interval interval = (Interval) o;
if (dst != interval.dst) return false;
if (src != interval.src) return false;
return true;
}
@Override
public int hashCode() {
int result = (int) (src ^ (src >>> 32));
result = 31 * result + (int) (dst ^ (dst >>> 32));
return result;
}
@Override
public int compareTo(Interval o) {
int c1 = Long.compare(src, o.src);
if (c1 != 0) {
return c1;
}
return Long.compare(dst, o.dst);
}
@Override
public String toString() {
return "[" + src + ", " + dst + "]";
}
}
| 2,252 | 31.185714 | 79 | java |
jmh | jmh-master/jmh-core/src/main/java/org/openjdk/jmh/util/IntervalMap.java | /*
* Copyright (c) 2014, 2021, 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 java.util.SortedMap;
import java.util.TreeMap;
public class IntervalMap<T> {
static final class Interval implements Comparable<Interval> {
final long from, to;
public Interval(long from, long to) {
this.from = from;
this.to = to;
}
@Override
public int compareTo(Interval other) {
return Long.compare(from, other.from);
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + (int) (from ^ (from >>> 32));
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
Interval other = (Interval) obj;
if (from != other.from) {
return false;
}
return true;
}
}
final SortedMap<Interval, T> from;
public IntervalMap() {
from = new TreeMap<>();
}
public void add(T val, long from, long to) {
// TODO: Check for intersections
this.from.put(new Interval(from, to), val);
}
public T get(long k) {
Interval i = new Interval(k, k);
T key = from.get(i);
if (key != null) {
return key;
}
SortedMap<Interval, T> head = from.headMap(i);
if (head.isEmpty()) {
return null;
} else {
Interval last = head.lastKey();
if (k >= last.from && k < last.to) {
return from.get(last); // Interval from..to contains k
} else {
return null;
}
}
}
public void merge(IntervalMap<T> other) {
from.putAll(other.from);
}
}
| 3,230 | 29.481132 | 79 | java |
jmh | jmh-master/jmh-core/src/main/java/org/openjdk/jmh/util/JDKVersion.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;
public class JDKVersion {
public static int parseMajor(String version) {
version = version.toLowerCase();
int dotIdx = version.indexOf(".");
if (dotIdx != -1) {
try {
return Integer.parseInt(version.substring(0, dotIdx));
} catch (Exception e) {
return -1;
}
}
int dashIdx = version.indexOf("-");
if (dashIdx != -1) {
try {
return Integer.parseInt(version.substring(0, dashIdx));
} catch (Exception e) {
return -1;
}
}
int uIdx = version.indexOf("u");
if (uIdx != -1) {
try {
return Integer.parseInt(version.substring(0, uIdx));
} catch (Exception e) {
return -1;
}
}
try {
return Integer.parseInt(version);
} catch (Exception e) {
return -1;
}
}
}
| 2,217 | 32.104478 | 76 | java |
jmh | jmh-master/jmh-core/src/main/java/org/openjdk/jmh/util/ListStatistics.java | /*
* Copyright (c) 2005, 2013, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package org.openjdk.jmh.util;
import org.apache.commons.math3.stat.descriptive.rank.Percentile;
import java.util.AbstractMap;
import java.util.Arrays;
import java.util.Iterator;
import java.util.Map;
import java.util.NoSuchElementException;
/**
* Calculate statistics over a list of doubles.
*/
public class ListStatistics extends AbstractStatistics {
private static final long serialVersionUID = -90642978235578197L;
private double[] values;
private int count;
public ListStatistics() {
values = new double[0];
count = 0;
}
public ListStatistics(double[] samples) {
this();
for (double d : samples) {
addValue(d);
}
}
public ListStatistics(long[] samples) {
this();
for (long l : samples) {
addValue((double) l);
}
}
public void addValue(double d) {
if (count >= values.length) {
values = Arrays.copyOf(values, Math.max(1, values.length << 1));
}
values[count] = d;
count++;
}
@Override
public double getMax() {
if (count > 0) {
double m = Double.NEGATIVE_INFINITY;
for (int i = 0; i < count; i++) {
m = Math.max(m, values[i]);
}
return m;
} else {
return Double.NaN;
}
}
@Override
public double getMin() {
if (count > 0) {
double m = Double.POSITIVE_INFINITY;
for (int i = 0; i < count; i++) {
m = Math.min(m, values[i]);
}
return m;
} else {
return Double.NaN;
}
}
@Override
public long getN() {
return count;
}
@Override
public double getSum() {
if (count > 0) {
double s = 0;
for (int i = 0; i < count; i++) {
s += values[i];
}
return s;
} else {
return Double.NaN;
}
}
@Override
public double getPercentile(double rank) {
if (count == 0) {
return Double.NaN;
}
if (rank == 0) {
return getMin();
}
// trim
values = Arrays.copyOf(values, count);
Percentile p = new Percentile();
return p.evaluate(values, rank);
}
@Override
public int[] getHistogram(double[] levels) {
if (levels.length < 2) {
throw new IllegalArgumentException("Expected more than two levels");
}
double[] vs = Arrays.copyOf(values, count);
Arrays.sort(vs);
int[] result = new int[levels.length - 1];
int c = 0;
values: for (double v : vs) {
while (levels[c] > v || v >= levels[c + 1]) {
c++;
if (c > levels.length - 2) break values;
}
result[c]++;
}
return result;
}
@Override
public Iterator<Map.Entry<Double, Long>> getRawData() {
return new ListStatisticsIterator();
}
@Override
public double getVariance() {
if (count > 1) {
double v = 0;
double m = getMean();
for (int i = 0; i < count; i++) {
v += Math.pow(values[i] - m, 2);
}
return v / (count - 1);
} else {
return Double.NaN;
}
}
private class ListStatisticsIterator implements Iterator<Map.Entry<Double, Long>> {
private int currentIndex = 0;
@Override
public boolean hasNext() {
return currentIndex < count;
}
@Override
public Map.Entry<Double, Long> next() {
if (!hasNext()) {
throw new NoSuchElementException("No more elements.");
}
return new AbstractMap.SimpleImmutableEntry<>(values[currentIndex++], 1L);
}
@Override
public void remove() {
throw new UnsupportedOperationException("Element cannot be removed.");
}
}
}
| 5,305 | 25.79798 | 87 | java |
jmh | jmh-master/jmh-core/src/main/java/org/openjdk/jmh/util/Multimap.java | /*
* Copyright (c) 2005, 2013, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package org.openjdk.jmh.util;
import java.util.Collection;
import java.util.Map;
/**
* Basic Multimap.
*
* @param <K> key type
* @param <V> value type
*/
public interface Multimap<K, V> {
/**
* Put the element pair.
*
* @param key key
* @param value value
*/
void put(K key, V value);
/**
* Put multiple pairs.
* @param k key
* @param vs values
*/
void putAll(K k, Collection<V> vs);
/**
* Get all values associated with the key
* @param key key
* @return collection of values
*/
Collection<V> get(K key);
/**
* Get all associations of the multimap.
* The method is intended for read-only view.
* @return entry set of the multimap
*/
Collection<Map.Entry<K, Collection<V>>> entrySet();
/**
* Checks if multimap is empty
* @return true, if empty
*/
boolean isEmpty();
/**
* Clears the multimap
*/
void clear();
/**
* Keys in the map
* @return collection of keys
*/
Collection<K> keys();
Collection<V> values();
void remove(K key);
void merge(Multimap<K, V> other);
}
| 2,390 | 25.274725 | 79 | java |
jmh | jmh-master/jmh-core/src/main/java/org/openjdk/jmh/util/Multiset.java | /*
* Copyright (c) 2005, 2022, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package org.openjdk.jmh.util;
import java.util.Collection;
import java.util.Map;
/**
* Basic Multiset.
*
* (Transitional interface)
*
* @param <T> element type
*/
public interface Multiset<T> {
/**
* Add the element to the multiset
* @param element element to add
*/
void add(T element);
/**
* Add the element to the multiset
* @param element element to add
* @param count number of elements to add
*/
void add(T element, long count);
/**
* Count the elements in multiset
* @param element element
* @return number of matching elements in the set; zero, if no elements
*/
long count(T element);
/**
* Get all associations of the multiset.
* Each entry provides a key and a count of that element.
* @return entry set of the multiset
*/
Collection<Map.Entry<T, Long>> entrySet();
/**
* Answers if Multiset is empty
* @return true, if set is empty
*/
boolean isEmpty();
/**
* Answers the size of multiset.
* Equivalent to number of elements, counting duplications.
*
* @return number of elements
*/
long size();
/**
* Answers the collection of keys
* @return the collections of keys
*/
Collection<T> keys();
/**
* Remove all the elements.
*/
void clear();
}
| 2,587 | 27.43956 | 79 | java |
jmh | jmh-master/jmh-core/src/main/java/org/openjdk/jmh/util/MultisetStatistics.java | /*
* Copyright (c) 2005, 2013, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package org.openjdk.jmh.util;
import java.util.*;
public class MultisetStatistics extends AbstractStatistics {
private static final long serialVersionUID = -4401871054963903938L;
private final Multiset<Double> values;
public MultisetStatistics() {
values = new TreeMultiset<>();
}
public void addValue(double d, long count) {
values.add(d, count);
}
@Override
public double getMax() {
if (!values.isEmpty()) {
double max = Double.NEGATIVE_INFINITY;
for (double d : values.keys()) {
max = Math.max(max, d);
}
return max;
} else {
return Double.NaN;
}
}
@Override
public double getMin() {
if (!values.isEmpty()) {
double min = Double.POSITIVE_INFINITY;
for (double d : values.keys()) {
min = Math.min(min, d);
}
return min;
} else {
return Double.NaN;
}
}
@Override
public long getN() {
return values.size();
}
@Override
public double getSum() {
if (!values.isEmpty()) {
double sum = 0;
for (double d : values.keys()) {
sum += d * values.count(d);
}
return sum;
} else {
return Double.NaN;
}
}
private double get(long index) {
long cur = 0;
for (double d : values.keys()) {
cur += values.count(d);
if (cur >= index) return d;
}
return getMax();
}
@Override
public double getPercentile(double rank) {
if (rank < 0.0d || rank > 100.0d)
throw new IllegalArgumentException("Rank should be within [0; 100]");
if (rank == 0.0d) {
return getMin();
}
double pos = rank * (values.size() + 1) / 100;
double floorPos = Math.floor(pos);
double flooredValue = get((long) floorPos);
double nextValue = get((long) floorPos + 1);
return flooredValue + (nextValue - flooredValue) * (pos - floorPos);
}
@Override
public double getVariance() {
if (getN() > 0) {
double v = 0;
double m = getMean();
for (double d : values.keys()) {
v += Math.pow(d - m, 2) * values.count(d);
}
return v / (getN() - 1);
} else {
return Double.NaN;
}
}
@Override
public int[] getHistogram(double[] levels) {
if (levels.length < 2) {
throw new IllegalArgumentException("Expected more than two levels");
}
List<Double> vs = new ArrayList<>(values.keys());
Collections.sort(vs);
int[] result = new int[levels.length - 1];
int c = 0;
values: for (double v : vs) {
while (levels[c] > v || v >= levels[c + 1]) {
c++;
if (c > levels.length - 2) break values;
}
result[c] += values.count(v);
}
return result;
}
@Override
public Iterator<Map.Entry<Double, Long>> getRawData() {
return values.entrySet().iterator();
}
}
| 4,472 | 27.858065 | 81 | java |
jmh | jmh-master/jmh-core/src/main/java/org/openjdk/jmh/util/Multisets.java | /*
* Copyright (c) 2005, 2013, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package org.openjdk.jmh.util;
import java.util.*;
public class Multisets {
public static <T> List<T> countHighest(Multiset<T> set, int top) {
Queue<Map.Entry<T, Long>> q = new BoundedPriorityQueue<>(top, Map.Entry.<T, Long>comparingByValue().reversed());
q.addAll(set.entrySet());
List<T> result = new ArrayList<>(q.size());
Map.Entry<T, Long> pair;
while ((pair = q.poll()) != null) {
result.add(pair.getKey());
}
// BoundedPriorityQueue returns "smallest to largest", so we reverse the result
Collections.reverse(result);
return result;
}
public static <T> List<T> sortedDesc(final Multiset<T> set) {
List<T> sorted = new ArrayList<>(set.keys());
sorted.sort((o1, o2) -> Long.compare(set.count(o2), set.count(o1)));
return sorted;
}
}
| 2,084 | 36.232143 | 120 | java |
jmh | jmh-master/jmh-core/src/main/java/org/openjdk/jmh/util/NullOutputStream.java | /*
* Copyright (c) 2014, 2014, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package org.openjdk.jmh.util;
import java.io.OutputStream;
public class NullOutputStream extends OutputStream {
@Override
public void write(byte[] b) {
// drop
}
@Override
public void write(byte[] b, int off, int len) {
// drop
}
@Override
public void write(int b) {
// drop
}
}
| 1,557 | 32.869565 | 79 | java |
jmh | jmh-master/jmh-core/src/main/java/org/openjdk/jmh/util/Optional.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.util;
import java.io.Serializable;
import java.util.Objects;
import java.util.function.Supplier;
/**
* Option class
* @param <T> stored value.
*/
public class Optional<T> implements Serializable {
private static final long serialVersionUID = 5691070564925468961L;
private final T val;
private Optional(T val) {
if (val == null) {
throw new IllegalArgumentException("Val can not be null");
}
this.val = val;
}
private Optional() {
this.val = null;
}
public T orElse(T elseVal) {
return (val == null) ? elseVal : val;
}
public T orElseGet(Supplier<T> alternativeSupplier) {
return (val == null) ? alternativeSupplier.get() : val;
}
public Optional<T> orAnother(Optional<T> alternative) {
return (val == null) ? alternative : this;
}
/**
* Produce empty Option
* @param <T> type
* @return empty option
*/
public static <T> Optional<T> none() {
return new Optional<>();
}
/**
* Wrap the existing value in Option.
* @param val value to wrap
* @param <T> type
* @return option with value
*/
public static <T> Optional<T> of(T val) {
return new Optional<>(val);
}
public static <T> Optional<T> eitherOf(T val) {
if (val == null) {
return Optional.none();
} else {
return Optional.of(val);
}
}
public boolean hasValue() {
return val != null;
}
public String toString() {
if (val == null) {
return "[]";
} else {
return "[" + val + "]";
}
}
public T get() {
if (val == null) {
throw new IllegalStateException("Optional is null");
}
return val;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Optional optional = (Optional) o;
if (!Objects.equals(val, optional.val)) return false;
return true;
}
@Override
public int hashCode() {
return val != null ? val.hashCode() : 0;
}
}
| 3,455 | 26.212598 | 79 | java |
jmh | jmh-master/jmh-core/src/main/java/org/openjdk/jmh/util/SampleBuffer.java | /*
* Copyright (c) 2005, 2013, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package org.openjdk.jmh.util;
import java.io.Serializable;
/**
* Sampling buffer accepts samples.
*/
public class SampleBuffer implements Serializable {
private static final long serialVersionUID = 6124923853916845327L;
private static final int PRECISION_BITS = 10;
private static final int BUCKETS = Long.SIZE - PRECISION_BITS;
private final int[][] hdr;
public SampleBuffer() {
hdr = new int[BUCKETS][];
}
public void half() {
for (int[] bucket : hdr) {
if (bucket != null) {
for (int j = 0; j < bucket.length; j++) {
int nV = bucket[j] / 2;
if (nV != 0) { // prevent halving to zero
bucket[j] = nV;
}
}
}
}
}
public void add(long sample) {
int bucket = Math.max(0, BUCKETS - Long.numberOfLeadingZeros(sample));
int subBucket = (int) (sample >> bucket);
int[] b = hdr[bucket];
if (b == null) {
b = new int[1 << PRECISION_BITS];
hdr[bucket] = b;
}
b[subBucket]++;
}
public Statistics getStatistics(double multiplier) {
MultisetStatistics stat = new MultisetStatistics();
for (int i = 0; i < hdr.length; i++) {
int[] bucket = hdr[i];
if (bucket != null) {
for (int j = 0; j < bucket.length; j++) {
long ns = (long) j << i;
stat.addValue(multiplier * ns, bucket[j]);
}
}
}
return stat;
}
public void addAll(SampleBuffer other) {
for (int i = 0; i < other.hdr.length; i++) {
int[] otherBucket = other.hdr[i];
if (otherBucket != null) {
int[] myBucket = hdr[i];
if (myBucket == null) {
myBucket = new int[1 << PRECISION_BITS];
hdr[i] = myBucket;
}
for (int j = 0; j < otherBucket.length; j++) {
myBucket[j] += otherBucket[j];
}
}
}
}
public int count() {
int count = 0;
for (int[] bucket : hdr) {
if (bucket != null) {
for (int v : bucket) {
count += v;
}
}
}
return count;
}
}
| 3,641 | 31.810811 | 79 | java |
jmh | jmh-master/jmh-core/src/main/java/org/openjdk/jmh/util/ScoreFormatter.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;
public class ScoreFormatter {
private static final int PRECISION = Integer.getInteger("jmh.scorePrecision", 3);
private static final double ULP = 1.0 / Math.pow(10, PRECISION);
private static final double THRESHOLD = ULP / 2;
public static boolean isApproximate(double score) {
return (score < THRESHOLD);
}
public static String format(double score) {
if (isApproximate(score)) {
int power = (int) Math.round(Math.log10(score));
return "\u2248 " + ((power != 0) ? "10" + superscript("" + power) : "0");
} else {
return String.format("%." + PRECISION + "f", score);
}
}
public static String format(int width, double score) {
if (isApproximate(score)) {
int power = (int) Math.round(Math.log10(score));
return String.format("%" + width + "s", "\u2248 " + ((power != 0) ? "10" + superscript("" + power) : "0"));
} else {
return String.format("%" + width + "." + PRECISION + "f", score);
}
}
public static String formatExact(int width, double score) {
return String.format("%" + width + "." + PRECISION + "f", score);
}
public static String formatLatex(double score) {
if (isApproximate(score)) {
int power = (int) Math.round(Math.log10(score));
return "$\\approx " + ((power != 0) ? "10^{" + power + "}" : "0") + "$";
} else {
return String.format("%." + PRECISION + "f", score);
}
}
public static String formatError(double error) {
return String.format("%." + PRECISION + "f", Math.max(error, ULP));
}
public static String formatError(int width, double error) {
return String.format("%" + width + "." + PRECISION + "f", Math.max(error, ULP));
}
public static String superscript(String str) {
str = str.replaceAll("-", "\u207b");
str = str.replaceAll("0", "\u2070");
str = str.replaceAll("1", "\u00b9");
str = str.replaceAll("2", "\u00b2");
str = str.replaceAll("3", "\u00b3");
str = str.replaceAll("4", "\u2074");
str = str.replaceAll("5", "\u2075");
str = str.replaceAll("6", "\u2076");
str = str.replaceAll("7", "\u2077");
str = str.replaceAll("8", "\u2078");
str = str.replaceAll("9", "\u2079");
return str;
}
}
| 3,651 | 38.695652 | 119 | java |
jmh | jmh-master/jmh-core/src/main/java/org/openjdk/jmh/util/SingletonStatistics.java | /*
* Copyright (c) 2005, 2013, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package org.openjdk.jmh.util;
import java.util.AbstractMap;
import java.util.Iterator;
import java.util.Map;
import java.util.NoSuchElementException;
/**
* Calculate statistics with just a single value.
*/
public class SingletonStatistics extends AbstractStatistics {
private static final long serialVersionUID = -90642978235578197L;
private final double value;
public SingletonStatistics(double value) {
this.value = value;
}
@Override
public double getMax() {
return value;
}
@Override
public double getMin() {
return value;
}
@Override
public long getN() {
return 1;
}
@Override
public double getSum() {
return value;
}
@Override
public double getPercentile(double rank) {
return value;
}
@Override
public double getVariance() {
return Double.NaN;
}
@Override
public int[] getHistogram(double[] levels) {
int[] result = new int[levels.length - 1];
for (int c = 0; c < levels.length - 1; c++) {
if (levels[c] <= value && value < levels[c + 1]) {
result[c] = 1;
break;
}
}
return result;
}
@Override
public Iterator<Map.Entry<Double, Long>> getRawData() {
return new SingletonStatisticsIterator();
}
private class SingletonStatisticsIterator implements Iterator<Map.Entry<Double, Long>> {
private boolean entryReturned = false;
@Override
public boolean hasNext() {
return !entryReturned;
}
@Override
public Map.Entry<Double, Long> next() {
if (entryReturned) {
throw new NoSuchElementException("No more elements.");
}
entryReturned = true;
return new AbstractMap.SimpleImmutableEntry<>(value, 1L);
}
@Override
public void remove() {
throw new UnsupportedOperationException("Element cannot be removed.");
}
}
}
| 3,283 | 27.556522 | 92 | java |
jmh | jmh-master/jmh-core/src/main/java/org/openjdk/jmh/util/Statistics.java | /*
* Copyright (c) 2005, 2013, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package org.openjdk.jmh.util;
import org.apache.commons.math3.stat.descriptive.StatisticalSummary;
import java.io.Serializable;
import java.util.Iterator;
import java.util.Map.Entry;
public interface Statistics extends Serializable, StatisticalSummary, Comparable<Statistics> {
/**
* Gets the confidence interval at given confidence level.
* @param confidence confidence level (e.g. 0.95)
* @return the interval in which mean lies with the given confidence level
*/
double[] getConfidenceIntervalAt(double confidence);
/**
* Gets the mean error at given confidence level.
* @param confidence confidence level (e.g. 0.95)
* @return the mean error with the given confidence level
*/
double getMeanErrorAt(double confidence);
/**
* Checks if this statistics statistically different from the given one
* with the given confidence level.
* @param other statistics to test against
* @param confidence confidence level (e.g. 0.95)
* @return true, if mean difference is statistically significant
*/
boolean isDifferent(Statistics other, double confidence);
/**
* Compares this statistics to another one.
* Follows the contract of {@link Comparable}.
*
* @param other statistics to compare against
* @return a negative integer, zero, or a positive integer as this statistics
* is less than, equal to, or greater than the specified statistics.
*/
int compareTo(Statistics other);
/**
* Compares this statistics to another one.
* Follows the contract of {@link Comparable}.
*
* @param other statistics to compare against
* @param confidence confidence level (e.g. 0.99)
* @return a negative integer, zero, or a positive integer as this statistics
* is less than, equal to, or greater than the specified statistics.
*/
int compareTo(Statistics other, double confidence);
/**
* Returns the maximum for this statistics.
* @return maximum
*/
double getMax();
/**
* Returns the minimum for this statistics.
* @return minimum
*/
double getMin();
/**
* Returns the arithmetic mean for this statistics.
* @return arithmetic mean
*/
double getMean();
/**
* Returns the number of samples in this statistics.
* @return number of samples
*/
long getN();
/**
* Returns the sum of samples in this statistics.
* @return sum
*/
double getSum();
/**
* Returns the standard deviation for this statistics.
* @return standard deviation
*/
double getStandardDeviation();
/**
* Returns the variance for this statistics.
* @return variance
*/
double getVariance();
/**
* Returns the percentile at given rank.
* @param rank the rank, [0..100]
* @return percentile
*/
double getPercentile(double rank);
/**
* Returns the histogram for this statistics. The histogram bin count would
* be equal to number of levels, minus one; so that each i-th bin is the
* number of samples in [i-th, (i+1)-th) levels.
*
* @param levels levels
* @return histogram data
*/
int[] getHistogram(double[] levels);
/**
* Returns the raw data for this statistics. This data can be useful for
* custom postprocessing and statistics computations. Note, that values of
* multiple calls may not be unique. Ordering of the values is not specified.
*
* @return iterator to raw data. Each item is pair of actual value and
* number of occurrences of this value.
*/
Iterator<Entry<Double, Long>> getRawData();
}
| 4,964 | 32.1 | 94 | java |
jmh | jmh-master/jmh-core/src/main/java/org/openjdk/jmh/util/TempFile.java | /*
* Copyright (c) 2016, Red Hat Inc.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package org.openjdk.jmh.util;
import java.io.*;
public class TempFile {
private final File file;
public TempFile(File file) {
this.file = file;
}
public void delete() {
file.delete();
}
public String getAbsolutePath() {
return file.getAbsolutePath();
}
public File file() {
return file;
}
}
| 1,534 | 30.979167 | 76 | java |
jmh | jmh-master/jmh-core/src/main/java/org/openjdk/jmh/util/TempFileManager.java | /*
* Copyright (c) 2016, Red Hat Inc.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package org.openjdk.jmh.util;
import java.io.File;
import java.io.IOException;
import java.lang.ref.ReferenceQueue;
import java.lang.ref.WeakReference;
import java.util.HashSet;
import java.util.Set;
public class TempFileManager {
private final ReferenceQueue<TempFile> rq;
private final Set<TempFileReference> refs;
public TempFileManager() {
rq = new ReferenceQueue<>();
refs = new HashSet<>();
}
public TempFile create(String suffix) throws IOException {
purge();
File file = File.createTempFile("jmh", suffix);
file.deleteOnExit();
TempFile tf = new TempFile(file);
refs.add(new TempFileReference(tf, rq));
return tf;
}
public void purge() {
TempFileReference ref;
while ((ref = (TempFileReference) rq.poll()) != null) {
if (ref.file != null) {
ref.file.delete();
}
refs.remove(ref);
}
}
private static class TempFileReference extends WeakReference<TempFile> {
final File file;
TempFileReference(TempFile referent, ReferenceQueue<? super TempFile> q) {
super(referent, q);
file = referent.file();
}
}
}
| 2,413 | 32.068493 | 82 | java |
jmh | jmh-master/jmh-core/src/main/java/org/openjdk/jmh/util/TreeMultimap.java | /*
* Copyright (c) 2005, 2013, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package org.openjdk.jmh.util;
import java.io.Serializable;
import java.util.Collection;
import java.util.TreeMap;
public class TreeMultimap<K, V> extends DelegatingMultimap<K, V> implements Serializable {
private static final long serialVersionUID = 1323519395777393861L;
public TreeMultimap() {
super(new TreeMap<>());
}
}
| 1,560 | 40.078947 | 90 | java |
jmh | jmh-master/jmh-core/src/main/java/org/openjdk/jmh/util/TreeMultiset.java | /*
* Copyright (c) 2005, 2013, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package org.openjdk.jmh.util;
import java.io.Serializable;
import java.util.TreeMap;
public class TreeMultiset<T extends Comparable<T>> extends DelegatingMultiset<T> implements Serializable {
private static final long serialVersionUID = 3571810468402616517L;
public TreeMultiset() {
super(new TreeMap<>());
}
}
| 1,547 | 40.837838 | 106 | java |
jmh | jmh-master/jmh-core/src/main/java/org/openjdk/jmh/util/UnCloseablePrintStream.java | /*
* Copyright (c) 2014, 2014, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package org.openjdk.jmh.util;
import java.io.OutputStream;
import java.io.PrintStream;
import java.io.UnsupportedEncodingException;
import java.nio.charset.Charset;
public class UnCloseablePrintStream extends PrintStream {
public UnCloseablePrintStream(OutputStream out, Charset charset) throws UnsupportedEncodingException {
super(out, false, charset.name());
}
@Override
public void close() {
// Do nothing.
}
}
| 1,667 | 37.790698 | 106 | java |
jmh | jmh-master/jmh-core/src/main/java/org/openjdk/jmh/util/Utils.java | /*
* Copyright (c) 2005, 2013, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package org.openjdk.jmh.util;
import sun.misc.Unsafe;
import java.io.*;
import java.lang.management.ManagementFactory;
import java.lang.reflect.AccessibleObject;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.nio.charset.Charset;
import java.util.*;
import java.util.concurrent.*;
public class Utils {
private static final Unsafe U;
static {
try {
Field unsafe = Unsafe.class.getDeclaredField("theUnsafe");
unsafe.setAccessible(true);
U = (Unsafe) unsafe.get(null);
} catch (NoSuchFieldException | IllegalAccessException e) {
throw new IllegalStateException(e);
}
}
private Utils() {
}
public static <T extends Comparable<T>> T min(Collection<T> ts) {
T min = null;
for (T t : ts) {
if (min == null) {
min = t;
} else {
min = min.compareTo(t) < 0 ? min : t;
}
}
return min;
}
public static <T extends Comparable<T>> T max(Collection<T> ts) {
T max = null;
for (T t : ts) {
if (max == null) {
max = t;
} else {
max = max.compareTo(t) > 0 ? max : t;
}
}
return max;
}
public static String[] concat(String[] t1, String[] t2) {
String[] r = new String[t1.length + t2.length];
System.arraycopy(t1, 0, r, 0, t1.length);
System.arraycopy(t2, 0, r, t1.length, t2.length);
return r;
}
public static String join(Collection<String> src, String delim) {
StringBuilder sb = new StringBuilder();
boolean first = true;
for (String s : src) {
if (first) {
first = false;
} else {
sb.append(delim);
}
sb.append(s);
}
return sb.toString();
}
public static String join(String[] src, String delim) {
return join(Arrays.asList(src), delim);
}
public static Collection<String> splitQuotedEscape(String src) {
List<String> results = new ArrayList<>();
StringBuilder sb = new StringBuilder();
boolean escaped = false;
for (char ch : src.toCharArray()) {
if (ch == ' ' && !escaped) {
String s = sb.toString();
if (!s.isEmpty()) {
results.add(s);
sb = new StringBuilder();
}
} else if (ch == '\"') {
escaped ^= true;
} else {
sb.append(ch);
}
}
String s = sb.toString();
if (!s.isEmpty()) {
results.add(s);
}
return results;
}
public static int sum(int[] arr) {
int sum = 0;
for (int i : arr) {
sum += i;
}
return sum;
}
public static int roundUp(int v, int quant) {
if ((v % quant) == 0) {
return v;
} else {
return ((v / quant) + 1)*quant;
}
}
public static String throwableToString(Throwable t) {
StringWriter sw = new StringWriter();
PrintWriter pw = new PrintWriter(sw);
t.printStackTrace(pw);
pw.flush();
pw.close();
return sw.toString();
}
public static int[] unmarshalIntArray(String src) {
String[] ss = src.split("=");
int[] arr = new int[ss.length];
int cnt = 0;
for (String s : ss) {
arr[cnt] = Integer.parseInt(s.trim());
cnt++;
}
return arr;
}
public static String marshalIntArray(int[] arr) {
StringBuilder sb = new StringBuilder();
for (int i : arr) {
sb.append(i);
sb.append("=");
}
return sb.toString();
}
/**
* Warm up the CPU schedulers, bring all the CPUs online to get the
* reasonable estimate of the system capacity. Some systems, notably embedded Linuxes,
* power down the idle CPUs and so availableProcessors() may report lower CPU count
* than would be present after the load-up.
*
* @return max CPU count
*/
public static int figureOutHotCPUs() {
ExecutorService service = Executors.newCachedThreadPool();
int warmupTime = 1000;
long lastChange = System.currentTimeMillis();
List<Future<?>> futures = new ArrayList<>();
futures.add(service.submit(new BurningTask()));
int max = 0;
while (System.currentTimeMillis() - lastChange < warmupTime) {
int cur = Runtime.getRuntime().availableProcessors();
if (cur > max) {
max = cur;
lastChange = System.currentTimeMillis();
futures.add(service.submit(new BurningTask()));
}
}
for (Future<?> f : futures) {
f.cancel(true);
}
service.shutdown();
return max;
}
private static void setAccessible(Object holder, AccessibleObject o) throws IllegalAccessException {
// JDK 9+ has the module protections in place, which would print the warning
// to the console if we try setAccessible(true) on inaccessible object.
// JDK 16 would deny access by default, so we have no recourse at all.
// Try to check with JDK 9+ AccessibleObject.canAccess before doing this
// to avoid the confusing console warnings. Force the break in if user asks
// explicitly.
if (!Boolean.getBoolean("jmh.forceSetAccessible")) {
try {
Method canAccess = AccessibleObject.class.getDeclaredMethod("canAccess", Object.class);
if (!(boolean) canAccess.invoke(o, holder)) {
throw new IllegalAccessException(o + " is not accessible");
}
} catch (NoSuchMethodException | InvocationTargetException e) {
// fall-through
}
}
o.setAccessible(true);
}
public static Charset guessConsoleEncoding() {
// The reason for this method to exist is simple: we need the proper platform encoding for output.
// We cannot use Console class directly, because we also need the access to the raw byte stream,
// e.g. for pushing in a raw output from a forked VM invocation. Therefore, we are left with
// reflectively poking out the Charset from Console, and use it for our own private output streams.
// Since JDK 17, there is Console.charset(), which we can use reflectively.
// Try 1. Try to poke the System.console().
Console console = System.console();
if (console != null) {
try {
Method m = Console.class.getDeclaredMethod("charset");
Object res = m.invoke(console);
if (res instanceof Charset) {
return (Charset) res;
}
} catch (Exception e) {
// fall-through
}
try {
Field f = Console.class.getDeclaredField("cs");
setAccessible(console, f);
Object res = f.get(console);
if (res instanceof Charset) {
return (Charset) res;
}
} catch (Exception e) {
// fall-through
}
try {
Method m = Console.class.getDeclaredMethod("encoding");
setAccessible(console, m);
Object res = m.invoke(null);
if (res instanceof String) {
return Charset.forName((String) res);
}
} catch (Exception e) {
// fall-through
}
}
// Try 2. Try to poke stdout.
// When System.console() is null, that is, an application is not attached to a console, the actual
// charset of standard output should be extracted from System.out, not from System.console().
// If we indeed have the console, but failed to poll its charset, it is still better to poke stdout.
try {
PrintStream out = System.out;
if (out != null) {
Field f = PrintStream.class.getDeclaredField("charOut");
setAccessible(out, f);
Object res = f.get(out);
if (res instanceof OutputStreamWriter) {
String encoding = ((OutputStreamWriter) res).getEncoding();
if (encoding != null) {
return Charset.forName(encoding);
}
}
}
} catch (Exception e) {
// fall-through
}
// Try 3. Try to poll internal properties.
String prop = System.getProperty("sun.stdout.encoding");
if (prop != null) {
try {
return Charset.forName(prop);
} catch (Exception e) {
// fall-through
}
}
// Try 4. Nothing left to do, except for returning a (possibly mismatched) default charset.
return Charset.defaultCharset();
}
public static void reflow(PrintWriter pw, String src, int width, int indent) {
StringTokenizer tokenizer = new StringTokenizer(src);
int curWidth = indent;
indent(pw, indent);
while (tokenizer.hasMoreTokens()) {
String next = tokenizer.nextToken();
pw.print(next);
pw.print(" ");
curWidth += next.length() + 1;
if (curWidth > width) {
pw.println();
indent(pw, indent);
curWidth = 0;
}
}
pw.println();
}
private static void indent(PrintWriter pw, int indent) {
for (int i = 0; i < indent; i++) {
pw.print(" ");
}
}
public static Collection<String> rewrap(String lines) {
Collection<String> result = new ArrayList<>();
String[] words = lines.split("[ \n]");
String line = "";
int cols = 0;
for (String w : words) {
cols += w.length();
line += w + " ";
if (cols > 40) {
result.add(line);
line = "";
cols = 0;
}
}
if (!line.trim().isEmpty()) {
result.add(line);
}
return result;
}
static class BurningTask implements Runnable {
@Override
public void run() {
while (!Thread.interrupted()); // burn;
}
}
public static void check(Class<?> klass, String... fieldNames) {
for (String fieldName : fieldNames) {
check(klass, fieldName);
}
}
public static void check(Class<?> klass, String fieldName) {
final long requiredGap = 128;
long markerBegin = getOffset(klass, "markerBegin");
long markerEnd = getOffset(klass, "markerEnd");
long off = getOffset(klass, fieldName);
if (markerEnd - off < requiredGap || off - markerBegin < requiredGap) {
throw new IllegalStateException("Consistency check failed for " + fieldName + ", off = " + off + ", markerBegin = " + markerBegin + ", markerEnd = " + markerEnd);
}
}
public static long getOffset(Class<?> klass, String fieldName) {
do {
try {
Field f = klass.getDeclaredField(fieldName);
return U.objectFieldOffset(f);
} catch (NoSuchFieldException e) {
// whatever, will try superclass
}
klass = klass.getSuperclass();
} while (klass != null);
throw new IllegalStateException("Can't find field \"" + fieldName + "\"");
}
public static boolean isWindows() {
return System.getProperty("os.name").contains("indows");
}
public static String getCurrentJvm() {
return System.getProperty("java.home") +
File.separator +
"bin" +
File.separator +
"java" +
(isWindows() ? ".exe" : "");
}
public static String getCurrentJvmVersion() {
return "JDK "
+ System.getProperty("java.version")
+ ", VM "
+ System.getProperty("java.vm.version");
}
public static String getCurrentOSVersion() {
return System.getProperty("os.name")
+ ", "
+ System.getProperty("os.arch")
+ ", "
+ System.getProperty("os.version");
}
/**
* Gets PID of the current JVM.
*
* @return PID.
*/
public static long getPid() {
final String DELIM = "@";
String name = ManagementFactory.getRuntimeMXBean().getName();
if (name != null) {
int idx = name.indexOf(DELIM);
if (idx != -1) {
String str = name.substring(0, name.indexOf(DELIM));
try {
return Long.parseLong(str);
} catch (NumberFormatException nfe) {
throw new IllegalStateException("Process PID is not a number: " + str);
}
}
}
throw new IllegalStateException("Unsupported PID format: " + name);
}
/**
* Gets the PID of the target process.
* @param process to poll
* @return PID, or zero if no PID is found
*/
public static long getPid(Process process) {
// Step 1. Try Process.pid, available since Java 9.
try {
Method m = Process.class.getMethod("pid");
Object pid = m.invoke(process);
if (pid instanceof Long) {
return (long) pid;
}
} catch (NoSuchMethodException | InvocationTargetException | IllegalAccessException e) {
// Fallthrough
}
// Step 2. Try to hack into the JDK 8- UNIXProcess.
try {
Class<?> c = Class.forName("java.lang.UNIXProcess");
Field f = c.getDeclaredField("pid");
setAccessible(process, f);
Object o = f.get(process);
if (o instanceof Integer) {
return (int) o;
}
} catch (NoSuchFieldException | ClassNotFoundException | IllegalAccessException e) {
// Fallthrough
}
// Step 3. Try to hack into JDK 9+ ProcessImpl.
// Renamed from UNIXProcess with JDK-8071481.
try {
Class<?> c = Class.forName("java.lang.ProcessImpl");
Field f = c.getDeclaredField("pid");
setAccessible(process, f);
Object o = f.get(process);
if (o instanceof Integer) {
return (int) o;
}
} catch (NoSuchFieldException | ClassNotFoundException | IllegalAccessException e) {
// Fallthrough
}
// No dice, return zero
return 0;
}
public static Collection<String> tryWith(String... cmd) {
Collection<String> messages = new ArrayList<>();
try {
Process p = new ProcessBuilder(cmd).start();
ByteArrayOutputStream baos = new ByteArrayOutputStream();
// drain streams, else we might lock up
InputStreamDrainer errDrainer = new InputStreamDrainer(p.getErrorStream(), baos);
InputStreamDrainer outDrainer = new InputStreamDrainer(p.getInputStream(), baos);
errDrainer.start();
outDrainer.start();
int err = p.waitFor();
errDrainer.join();
outDrainer.join();
if (err != 0) {
messages.add(baos.toString());
}
} catch (IOException ex) {
return Collections.singleton(ex.getMessage());
} catch (InterruptedException ex) {
throw new IllegalStateException(ex);
}
return messages;
}
public static Process runAsync(String... cmd) {
try {
return new ProcessBuilder(cmd).start();
} catch (IOException ex) {
throw new IllegalStateException(ex);
}
}
public static Collection<String> runWith(String... cmds) {
return runWith(Arrays.asList(cmds));
}
public static Collection<String> runWith(List<String> cmd) {
Collection<String> messages = new ArrayList<>();
try {
Process p = new ProcessBuilder(cmd).start();
ByteArrayOutputStream baos = new ByteArrayOutputStream();
// drain streams, else we might lock up
InputStreamDrainer errDrainer = new InputStreamDrainer(p.getErrorStream(), baos);
InputStreamDrainer outDrainer = new InputStreamDrainer(p.getInputStream(), baos);
errDrainer.start();
outDrainer.start();
int err = p.waitFor();
errDrainer.join();
outDrainer.join();
messages.add(baos.toString());
} catch (IOException ex) {
return Collections.singleton(ex.getMessage());
} catch (InterruptedException ex) {
throw new IllegalStateException(ex);
}
return messages;
}
/**
* We don't access the complete system properties via {@link System#getProperties()} because
* this would require read/write permissions to the properties. Just copy the properties we
* want to record in the result.
*
* @return Copy of system properties we want to record in the results.
*/
public static Properties getRecordedSystemProperties() {
String[] names = new String[]{"java.version", "java.vm.version", "java.vm.name"};
Properties p = new Properties();
for (String i : names) {
p.setProperty(i, System.getProperty(i));
}
return p;
}
public static Properties readPropertiesFromCommand(List<String> cmd) {
Properties out = new Properties();
try {
File tempFile = FileUtils.tempFile("properties");
List<String> cmdWithFile = new ArrayList<>(cmd);
cmdWithFile.add(tempFile.getAbsolutePath());
Collection<String> errs = tryWith(cmdWithFile.toArray(new String[0]));
if (!errs.isEmpty()) {
throw new RuntimeException("Unable to extract forked JVM properties using: '" + join(cmd, " ") + "'; " + errs);
}
try (InputStream in = new BufferedInputStream(new FileInputStream(tempFile))) {
// This will automatically pick UTF-8 based on the encoding in the XML declaration.
out.loadFromXML(in);
}
} catch (IOException ex) {
throw new RuntimeException(ex);
}
return out;
}
/**
* Adapts Iterator for Iterable.
* Can be iterated only once!
*
* @param <T> element type
* @param it iterator
* @return iterable for given iterator
*/
public static <T> Iterable<T> adaptForLoop(final Iterator<T> it) {
return () -> it;
}
}
| 20,534 | 32.499184 | 174 | java |
jmh | jmh-master/jmh-core/src/main/java/org/openjdk/jmh/util/Version.java | /*
* Copyright (c) 2014, 2014, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package org.openjdk.jmh.util;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
import java.util.Properties;
import java.util.concurrent.TimeUnit;
public class Version {
private static final int UPDATE_INTERVAL = 180;
/**
* @return the version, build date and update hint.
*/
public static String getVersion() {
StringWriter sw = new StringWriter();
PrintWriter pw = new PrintWriter(sw);
printVersion(pw);
pw.close();
return sw.toString();
}
/**
* @return only version, e.g. "1.19", or "-" if the version cannot be determined.
*/
public static String getPlainVersion() {
Properties p = new Properties();
InputStream s = Version.class.getResourceAsStream("/jmh.properties");
if (s == null) {
return "-";
}
try {
p.load(s);
} catch (IOException e) {
return "-";
} finally {
FileUtils.safelyClose(s);
}
String version = (String) p.get("jmh.version");
if (version == null) {
return "-";
}
return version;
}
private static void printVersion(PrintWriter pw) {
Properties p = new Properties();
InputStream s = Version.class.getResourceAsStream("/jmh.properties");
if (s == null) {
pw.print("Cannot figure out JMH version, no jmh.properties");
return;
}
try {
p.load(s);
} catch (IOException e) {
pw.print("Cannot figure out JMH version");
return;
} finally {
FileUtils.safelyClose(s);
}
String version = (String) p.get("jmh.version");
if (version == null) {
pw.print("Cannot read jmh.version");
return;
}
pw.print("JMH " + version + " ");
String time = (String) p.get("jmh.buildDate");
if (time == null) {
pw.print("(cannot read jmh.buildDate)");
return;
}
pw.print("(released ");
try {
Date parse = new SimpleDateFormat("yyyy/MM/dd", Locale.ROOT).parse(time);
long diff = (System.currentTimeMillis() - parse.getTime()) / TimeUnit.DAYS.toMillis(1);
if (diff > 0) {
pw.print(String.format("%d days ago", diff));
if (diff > UPDATE_INTERVAL) {
pw.print(", please consider updating!");
}
} else {
pw.print("today");
}
} catch (ParseException e) {
pw.print(time);
}
pw.print(")");
}
}
| 4,067 | 30.78125 | 99 | java |
jmh | jmh-master/jmh-core/src/main/java/org/openjdk/jmh/util/lines/Armor.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;
/**
* This implements a simple String armoring scheme that resembles Base64.
* We cannot use Base64 implementations from JDK yet, because the lowest language level is at 7.
*/
class Armor {
// 64 characters, plus a padding symbol at the end.
static final String DICT = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
private static void encodeStep(int[] ibuf, int[] obuf) {
obuf[0] = ((ibuf[0] & 0x3F) );
obuf[1] = ((ibuf[0] & 0xFF) >> 6) + ((ibuf[1] & 0xF) << 2);
obuf[2] = ((ibuf[1] & 0xFF) >> 4) + ((ibuf[2] & 0x3) << 4);
obuf[3] = ((ibuf[2] & 0xFF) >> 2);
obuf[4] = ((ibuf[3] & 0x3F) );
obuf[5] = ((ibuf[3] & 0xFF) >> 6) + ((ibuf[4] & 0xF) << 2);
obuf[6] = ((ibuf[4] & 0xFF) >> 4) + ((ibuf[5] & 0x3) << 4);
obuf[7] = ((ibuf[5] & 0xFF) >> 2);
}
private static void decodeStep(int[] ibuf, int[] obuf) {
obuf[0] = (((ibuf[0] & 0xFF) ) + ((ibuf[1] & 0x3) << 6));
obuf[1] = (((ibuf[1] & 0xFF) >> 2) + ((ibuf[2] & 0xF) << 4));
obuf[2] = (((ibuf[2] & 0xFF) >> 4) + ((ibuf[3] & 0x3F) << 2));
obuf[3] = (((ibuf[4] & 0xFF) ) + ((ibuf[5] & 0x3) << 6));
obuf[4] = (((ibuf[5] & 0xFF) >> 2) + ((ibuf[6] & 0xF) << 4));
obuf[5] = (((ibuf[6] & 0xFF) >> 4) + ((ibuf[7] & 0x3F) << 2));
}
public static String encode(String src) {
StringBuilder sb = new StringBuilder();
char[] chars = src.toCharArray();
int[] ibuf = new int[6];
int[] obuf = new int[8];
for (int c = 0; c < chars.length / 3; c++) {
for (int i = 0; i < 3; i++) {
ibuf[i*2 + 0] = chars[c*3 + i] & 0xFF;
ibuf[i*2 + 1] = (chars[c*3 + i] >> 8) & 0xFF;
}
encodeStep(ibuf, obuf);
for (int i = 0; i < 8; i++) {
sb.append(DICT.charAt(obuf[i]));
}
}
int tail = chars.length % 3;
if (tail != 0) {
int tailStart = chars.length / 3 * 3;
char PAD = DICT.charAt(DICT.length() - 1);
for (int i = 0; i < tail; i++) {
ibuf[i*2 + 0] = chars[tailStart + i] & 0xFF;
ibuf[i*2 + 1] = (chars[tailStart + i] >> 8) & 0xFF;
}
for (int i = tail; i < 3; i++) {
ibuf[i*2 + 0] = 0;
ibuf[i*2 + 1] = 0;
}
encodeStep(ibuf, obuf);
for (int i = 0; i < tail*3; i++) {
sb.append(DICT.charAt(obuf[i]));
}
for (int i = tail*3; i < 8; i++) {
sb.append(PAD);
}
}
return sb.toString();
}
public static String decode(String encoded) {
char[] encChars = encoded.toCharArray();
char[] decChars = new char[encChars.length / 8 * 3];
if (encChars.length % 8 != 0) {
throw new IllegalArgumentException("The length should be multiple of 8");
}
final int PAD_IDX = DICT.length() - 1;
int[] ibuf = new int[8];
int[] obuf = new int[6];
int oLen = 0;
int cut = 0;
for (int c = 0; c < encChars.length/8; c++) {
for (int i = 0; i < 8; i++) {
ibuf[i] = DICT.indexOf(encChars[c*8 + i]);
}
if (ibuf[3] == PAD_IDX) {
for (int i = 3; i < 8; i++) {
ibuf[i] = 0;
}
cut = 2;
} else if (ibuf[6] == PAD_IDX) {
for (int i = 6; i < 8; i++) {
ibuf[i] = 0;
}
cut = 1;
}
decodeStep(ibuf, obuf);
decChars[oLen++] = (char)(obuf[0] + (obuf[1] << 8));
decChars[oLen++] = (char)(obuf[2] + (obuf[3] << 8));
decChars[oLen++] = (char)(obuf[4] + (obuf[5] << 8));
}
return new String(decChars, 0, decChars.length - cut);
}
}
| 5,242 | 34.425676 | 99 | java |
jmh | jmh-master/jmh-core/src/main/java/org/openjdk/jmh/util/lines/Constants.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;
public class Constants {
public static final String MAGIC = "JMH ";
public static final char TAG_EMPTY_OPTIONAL = 'E';
public static final char TAG_STRING = 'S';
public static final char TAG_INT = 'I';
public static final char TAG_TIMEVALUE = 'T';
public static final char TAG_STRING_COLLECTION = 'L';
public static final char TAG_INT_ARRAY = 'A';
public static final char TAG_PARAM_MAP = 'M';
public static final char TAG_TIMEUNIT = 'U';
}
| 1,798 | 43.975 | 79 | java |
jmh | jmh-master/jmh-core/src/main/java/org/openjdk/jmh/util/lines/TestLineReader.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.openjdk.jmh.runner.options.TimeValue;
import org.openjdk.jmh.util.Optional;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import static org.openjdk.jmh.util.lines.Constants.*;
public class TestLineReader {
private final String line;
private final boolean correct;
private int cursor;
public TestLineReader(String line) {
this.line = line;
this.correct = (line.length() > MAGIC.length() && line.startsWith(MAGIC));
this.cursor = MAGIC.length();
}
private int readLen() {
StringBuilder sb = new StringBuilder();
char c = line.charAt(cursor);
while (Character.isDigit(c)) {
sb.append(c);
cursor++;
c = line.charAt(cursor);
}
cursor++;
return Integer.parseInt(sb.toString());
}
private String readString() {
int len = readLen();
String s = line.substring(cursor, cursor + len);
cursor += len + 1;
return s;
}
private String readArmoredString() {
return Armor.decode(readString());
}
private char readChar() {
char c = line.charAt(cursor);
cursor += 2;
return c;
}
public String nextString() {
char tag = readChar();
if (tag == TAG_STRING) {
return readString();
} else {
throw error("unexpected tag = " + tag);
}
}
private RuntimeException error(String msg) {
return new IllegalStateException("Error: " + msg + "\n at \"" + line + "\", pos " + cursor);
}
public boolean isCorrect() {
return correct;
}
public Optional<Integer> nextOptionalInt() {
char tag = readChar();
if (tag == Constants.TAG_EMPTY_OPTIONAL) {
return Optional.none();
} else if (tag == TAG_INT) {
return Optional.of(Integer.valueOf(readString()));
} else {
throw error("unexpected tag = " + tag);
}
}
public Optional<String> nextOptionalString() {
char tag = readChar();
if (tag == Constants.TAG_EMPTY_OPTIONAL) {
return Optional.none();
} else if (tag == TAG_STRING) {
return Optional.of(readString());
} else {
throw error("unexpected tag = " + tag);
}
}
public Optional<TimeValue> nextOptionalTimeValue() {
char tag = readChar();
if (tag == Constants.TAG_EMPTY_OPTIONAL) {
return Optional.none();
} else if (tag == TAG_TIMEVALUE) {
return Optional.of(TimeValue.fromString(readString()));
} else {
throw error("unexpected tag = " + tag);
}
}
public Optional<TimeUnit> nextOptionalTimeUnit() {
char tag = readChar();
if (tag == Constants.TAG_EMPTY_OPTIONAL) {
return Optional.none();
} else if (tag == TAG_TIMEUNIT) {
return Optional.of(TimeUnit.valueOf(readString()));
} else {
throw error("unexpected tag = " + tag);
}
}
public Optional<Collection<String>> nextOptionalStringCollection() {
char tag = readChar();
if (tag == Constants.TAG_EMPTY_OPTIONAL) {
return Optional.none();
} else if (tag == TAG_STRING_COLLECTION) {
int len = readLen();
Collection<String> list = new ArrayList<>();
for (int c = 0; c < len; c++) {
list.add(readString());
}
return Optional.of(list);
} else {
throw error("unexpected tag = " + tag);
}
}
public int[] nextIntArray() {
char tag = readChar();
if (tag == TAG_INT_ARRAY) {
int len = readLen();
int[] rs = new int[len];
for (int c = 0; c < len; c++) {
rs[c] = Integer.parseInt(readString());
}
return rs;
} else {
throw error("unexpected tag = " + tag);
}
}
public Optional<Map<String, String[]>> nextOptionalParamCollection() {
char tag = readChar();
if (tag == Constants.TAG_EMPTY_OPTIONAL) {
return Optional.none();
} else if (tag == TAG_PARAM_MAP) {
Map<String, String[]> result = new HashMap<>();
int kvs = readLen();
for (int kv = 0; kv < kvs; kv++) {
String key = readString();
int vlen = readLen();
String[] values = new String[vlen];
for (int v = 0; v < vlen; v++) {
values[v] = readArmoredString();
}
result.put(key, values);
}
return Optional.of(result);
} else {
throw error("unexpected tag = " + tag);
}
}
}
| 6,182 | 30.707692 | 100 | java |
jmh | jmh-master/jmh-core/src/main/java/org/openjdk/jmh/util/lines/TestLineWriter.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.openjdk.jmh.runner.options.TimeValue;
import org.openjdk.jmh.util.Optional;
import java.util.Collection;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import static org.openjdk.jmh.util.lines.Constants.*;
public class TestLineWriter {
private final StringBuilder line;
public TestLineWriter() {
line = new StringBuilder();
line.append(MAGIC);
}
private void appendWithLen(String s) {
appendLen(s.length());
line.append(s);
line.append(" ");
}
private void appendArmoredWithLen(String s) {
String as = Armor.encode(s);
appendLen(as.length());
line.append(as);
line.append(" ");
}
private void appendLen(int len) {
line.append(len);
line.append(" ");
}
private void appendTag(char tag) {
line.append(tag);
line.append(" ");
}
public void putString(String s) {
appendTag(TAG_STRING);
appendWithLen(s);
}
public void putOptionalInt(Optional<Integer> opt) {
if (!opt.hasValue()) {
appendTag(TAG_EMPTY_OPTIONAL);
} else {
appendTag(TAG_INT);
appendWithLen(String.valueOf(opt.get()));
}
}
public void putOptionalString(Optional<String> opt) {
if (!opt.hasValue()) {
appendTag(TAG_EMPTY_OPTIONAL);
} else {
appendTag(TAG_STRING);
appendWithLen(opt.get());
}
}
public void putIntArray(int[] arr) {
appendTag(TAG_INT_ARRAY);
appendLen(arr.length);
for (int v : arr) {
appendWithLen(String.valueOf(v));
}
}
public void putOptionalStringCollection(Optional<Collection<String>> opt) {
if (!opt.hasValue()) {
appendTag(TAG_EMPTY_OPTIONAL);
} else {
appendTag(TAG_STRING_COLLECTION);
Collection<String> coll = opt.get();
appendLen(coll.size());
for (String s : coll) {
appendWithLen(s);
}
}
}
public void putOptionalTimeValue(Optional<TimeValue> opt) {
if (!opt.hasValue()) {
appendTag(TAG_EMPTY_OPTIONAL);
} else {
appendTag(TAG_TIMEVALUE);
appendWithLen(opt.get().toString());
}
}
public void putOptionalTimeUnit(Optional<TimeUnit> opt) {
if (!opt.hasValue()) {
appendTag(TAG_EMPTY_OPTIONAL);
} else {
appendTag(TAG_TIMEUNIT);
appendWithLen(opt.get().toString());
}
}
public void putOptionalParamCollection(Optional<Map<String, String[]>> opt) {
if (!opt.hasValue()) {
appendTag(TAG_EMPTY_OPTIONAL);
} else {
appendTag(TAG_PARAM_MAP);
Map<String, String[]> map = opt.get();
appendLen(map.size());
for (String key : map.keySet()) {
appendWithLen(key);
String[] vals = map.get(key);
appendLen(vals.length);
for (String value : vals) {
appendArmoredWithLen(value);
}
}
}
}
@Override
public String toString() {
return line.toString();
}
}
| 4,560 | 27.867089 | 81 | java |
jmh | jmh-master/jmh-core/src/test/java/org/openjdk/jmh/BlackholeTest.java | /*
* Copyright (c) 2005, 2013, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package org.openjdk.jmh;
import org.junit.Assert;
import org.junit.Test;
import org.openjdk.jmh.infra.Blackhole;
public class BlackholeTest {
@Test
public void test() {
int tlr = 1;
int tlrMask = 2;
for (int t = 0; t < 1_000_000_000; t++) {
tlr = (tlr * 48271);
if ((tlr & tlrMask) == 0) {
// SHOULD ALMOST NEVER HAPPEN IN MEASUREMENT
tlrMask = (tlrMask << 1) + 2;
System.out.println(t);
}
}
}
@Test
public void testUserConstructor() {
try {
new Blackhole("Boyaa");
Assert.fail("Should have failed");
} catch (IllegalStateException e) {
// expected
}
try {
new Blackhole("Today's password is swordfish. I understand instantiating Blackholes directly is dangerous.");
} catch (Throwable e) {
Assert.fail("Failed unexpectedly");
}
}
}
| 2,200 | 33.390625 | 121 | java |
jmh | jmh-master/jmh-core/src/test/java/org/openjdk/jmh/generators/core/BenchmarkGeneratorTest.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.generators.core;
import org.junit.Assert;
import org.junit.Test;
import java.util.concurrent.ThreadLocalRandom;
public class BenchmarkGeneratorTest {
static final int TAB_SIZE = 4;
@Test
public void testIndentsForward() {
for (int c = 0; c < 10; c++) {
BenchmarkGenerator.INDENTS = null;
Assert.assertEquals(c*TAB_SIZE, BenchmarkGenerator.ident(c).length());
}
}
@Test
public void testIndentsBackwards() {
for (int c = 10; c >= 0; c--) {
BenchmarkGenerator.INDENTS = null;
Assert.assertEquals(c*TAB_SIZE, BenchmarkGenerator.ident(c).length());
}
}
@Test
public void testIndentsRandom() {
for (int c = 0; c < 10; c++) {
BenchmarkGenerator.INDENTS = null;
int i = ThreadLocalRandom.current().nextInt(10);
Assert.assertEquals(i*TAB_SIZE, BenchmarkGenerator.ident(i).length());
}
}
}
| 2,197 | 34.451613 | 82 | java |
jmh | jmh-master/jmh-core/src/test/java/org/openjdk/jmh/profile/PerfAsmAddressTest.java | /*
* Copyright Amazon.com Inc. or its affiliates. All Rights Reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package org.openjdk.jmh.profile;
import org.junit.Assert;
import org.junit.Test;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
public class PerfAsmAddressTest {
static final HashMap<String, List<Long>> TESTS = new HashMap<>();
static long addr(String s) {
return Long.parseLong(s, 16);
}
static {
TESTS.put("0x00007f815c65724e: test %eax,(%r8)",
Arrays.asList(addr("7f815c65724e")));
TESTS.put("0x00007f815c657239: je 0x00007f815c657290",
Arrays.asList(addr("7f815c657239"), addr("7f815c657290")));
TESTS.put("0x00007f815c657256: movabs $0x7f8171798570,%r10",
Arrays.asList(addr("7f815c657256"), addr("7f8171798570")));
TESTS.put("0x0000ffff685c7d2c: b 0x0000ffff685c7cf0",
Arrays.asList(addr("ffff685c7d2c"), addr("ffff685c7cf0")));
TESTS.put("0x0000ffff685c7d1c: b.ne 0x0000ffff685c7cb4 // b.any",
Arrays.asList(addr("ffff685c7d1c"), addr("ffff685c7cb4")));
TESTS.put("0x0000ffff685c7d1c: b.ne 0x0000ffff685c7cb4// b.any",
Arrays.asList(addr("ffff685c7d1c"), addr("ffff685c7cb4")));
TESTS.put("0x0000ffff685c7d1c: b.ne 0x0000ffff685c7cb4;comment",
Arrays.asList(addr("ffff685c7d1c"), addr("ffff685c7cb4")));
TESTS.put("0x0000ffff685c7d1c:b.ne 0x0000ffff685c7cb4",
Arrays.asList(addr("ffff685c7d1c"), addr("ffff685c7cb4")));
TESTS.put("0x0000ffff685c7d1c: b.ne\t0x0000ffff685c7cb4",
Arrays.asList(addr("ffff685c7d1c"), addr("ffff685c7cb4")));
}
@Test
public void testNoPrefix() {
List<Long> empty = new ArrayList<>();
for (String line : TESTS.keySet()) {
List<Long> expected = TESTS.get(line);
String leadingSpace = " " + line;
String trailingSpace = line + " ";
Assert.assertEquals(line, expected, AbstractPerfAsmProfiler.parseAddresses(line, false, true));
Assert.assertEquals(line, expected, AbstractPerfAsmProfiler.parseAddresses(leadingSpace, false, true));
Assert.assertEquals(line, empty, AbstractPerfAsmProfiler.parseAddresses(leadingSpace, true, true));
Assert.assertEquals(line, expected, AbstractPerfAsmProfiler.parseAddresses(trailingSpace, false, true));
Assert.assertEquals(line, expected, AbstractPerfAsmProfiler.parseAddresses(trailingSpace, true, true));
}
}
@Test
public void testPrefix() {
List<Long> empty = new ArrayList<>();
for (String line : TESTS.keySet()) {
List<Long> expected = TESTS.get(line);
String prefixedLine = "something " + line;
String prefixedLeadingLine = " something " + line;
String prefixedTrailingLine = "something " + line + " ";
Assert.assertEquals(line, empty, AbstractPerfAsmProfiler.parseAddresses(prefixedLine, false, true));
Assert.assertEquals(line, empty, AbstractPerfAsmProfiler.parseAddresses(prefixedLeadingLine, false, true));
Assert.assertEquals(line, empty, AbstractPerfAsmProfiler.parseAddresses(prefixedTrailingLine, false, true));
Assert.assertEquals(line, empty, AbstractPerfAsmProfiler.parseAddresses(prefixedLine, true, true));
Assert.assertEquals(line, empty, AbstractPerfAsmProfiler.parseAddresses(prefixedLeadingLine, true, true));
Assert.assertEquals(line, empty, AbstractPerfAsmProfiler.parseAddresses(prefixedTrailingLine, true, true));
Assert.assertEquals(line, expected, AbstractPerfAsmProfiler.parseAddresses(prefixedLine, false, false));
Assert.assertEquals(line, expected, AbstractPerfAsmProfiler.parseAddresses(prefixedLeadingLine, false, false));
Assert.assertEquals(line, expected, AbstractPerfAsmProfiler.parseAddresses(prefixedTrailingLine, false, false));
Assert.assertEquals(line, expected, AbstractPerfAsmProfiler.parseAddresses(prefixedLine, true, false));
Assert.assertEquals(line, expected, AbstractPerfAsmProfiler.parseAddresses(prefixedLeadingLine, true, false));
Assert.assertEquals(line, expected, AbstractPerfAsmProfiler.parseAddresses(prefixedTrailingLine, true, false));
}
}
}
| 5,700 | 46.508333 | 124 | java |
jmh | jmh-master/jmh-core/src/test/java/org/openjdk/jmh/profile/PerfParseTest.java | /*
* Copyright (c) 2016, Red Hat Inc.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package org.openjdk.jmh.profile;
import org.junit.Assert;
import org.junit.Test;
import java.util.ArrayList;
import java.util.List;
public class PerfParseTest {
private static final double ASSERT_ACCURACY = 0.0000001;
@Test
public void parsePerf_4_4() {
String[] lines = new String[] {
"328650.667569: instructions: 7f82b6a8beb4 ConstantPoolCache::allocate (/somewhere/on/my/filesystem/libjvm.so)",
"328650.667569: instructions: 7f82b6a8beb4 ConstantPoolCache::allocate (/somewhere/on/my/filesystem/with spaces/libjvm.so)"
};
for (String line : lines) {
LinuxPerfAsmProfiler.PerfLine perfLine = LinuxPerfAsmProfiler.parsePerfLine(line);
Assert.assertEquals(328650.667569D, perfLine.time(), ASSERT_ACCURACY);
Assert.assertEquals("instructions", perfLine.eventName());
Assert.assertEquals(0x7f82b6a8beb4L, perfLine.addr());
Assert.assertEquals("ConstantPoolCache::allocate", perfLine.symbol());
Assert.assertEquals("libjvm.so", perfLine.lib());
}
}
@Test
public void parseRaggedSymbols() {
String[] lines = new String[] {
"328650.667569: instructions: 7f82b6a8beb4 ConstantPoolCache::allocate(Thread* thr) (/somewhere/on/my/filesystem/libjvm.so)",
};
for (String line : lines) {
LinuxPerfAsmProfiler.PerfLine perfLine = LinuxPerfAsmProfiler.parsePerfLine(line);
Assert.assertEquals(328650.667569D, perfLine.time(), ASSERT_ACCURACY);
Assert.assertEquals("instructions", perfLine.eventName());
Assert.assertEquals(0x7f82b6a8beb4L, perfLine.addr());
Assert.assertEquals("ConstantPoolCache::allocate(Thread* thr)", perfLine.symbol());
Assert.assertEquals("libjvm.so", perfLine.lib());
}
}
@Test
public void parseOptionalTag() {
String[] lines = new String[] {
"328650.667569: instructions:u: 7f82b6a8beb4 ConstantPoolCache::allocate (/somewhere/on/my/filesystem/libjvm.so)",
"328650.667569: instructions:uk: 7f82b6a8beb4 ConstantPoolCache::allocate (/somewhere/on/my/filesystem/libjvm.so)",
"328650.667569: instructions:k: 7f82b6a8beb4 ConstantPoolCache::allocate (/somewhere/on/my/filesystem/libjvm.so)",
"328650.667569: instructions:HG: 7f82b6a8beb4 ConstantPoolCache::allocate (/somewhere/on/my/filesystem/libjvm.so)",
"328650.667569: instructions:H: 7f82b6a8beb4 ConstantPoolCache::allocate (/somewhere/on/my/filesystem/libjvm.so)",
"328650.667569: instructions:: 7f82b6a8beb4 ConstantPoolCache::allocate (/somewhere/on/my/filesystem/libjvm.so)"
};
for (String line : lines) {
LinuxPerfAsmProfiler.PerfLine perfLine = LinuxPerfAsmProfiler.parsePerfLine(line);
Assert.assertEquals(328650.667569D, perfLine.time(), ASSERT_ACCURACY);
Assert.assertEquals("instructions", perfLine.eventName());
Assert.assertEquals(0x7f82b6a8beb4L, perfLine.addr());
Assert.assertEquals("ConstantPoolCache::allocate", perfLine.symbol());
Assert.assertEquals("libjvm.so", perfLine.lib());
}
}
@Test
public void stripEvents() {
List<String> list = new ArrayList<>();
list.add("cycles");
list.add("instructions:u:");
list.add("branches:pppu:");
List<String> stripped = LinuxPerfAsmProfiler.stripPerfEventNames(list);
Assert.assertEquals("cycles", stripped.get(0));
Assert.assertEquals("instructions", stripped.get(1));
Assert.assertEquals("branches", stripped.get(2));
}
}
| 4,945 | 45.660377 | 146 | java |
jmh | jmh-master/jmh-core/src/test/java/org/openjdk/jmh/profile/SafepointsProfilerTest.java | /*
* Copyright (c) 2016, Red Hat Inc.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package org.openjdk.jmh.profile;
import org.junit.Assert;
import org.junit.Test;
public class SafepointsProfilerTest {
@Test
public void parseJDK7u77_Point() {
SafepointsProfiler.ParsedData data = SafepointsProfiler.parse(
"1.095: Total time for which application threads were stopped: 0.0014010 seconds");
Assert.assertNotNull(data);
Assert.assertEquals(1_095_000_000L, data.timestamp);
Assert.assertEquals( 1_401_000L, data.stopTime);
Assert.assertEquals(Long.MIN_VALUE, data.ttspTime);
}
@Test
public void parseJDK7u77_Comma() {
SafepointsProfiler.ParsedData data = SafepointsProfiler.parse(
"1,095: Total time for which application threads were stopped: 0,0014010 seconds");
Assert.assertNotNull(data);
Assert.assertEquals(1_095_000_000L, data.timestamp);
Assert.assertEquals( 1_401_000L, data.stopTime);
Assert.assertEquals(Long.MIN_VALUE, data.ttspTime);
}
@Test
public void parseJDK8u101_Dot() {
SafepointsProfiler.ParsedData data = SafepointsProfiler.parse(
"5.042: Total time for which application threads were stopped: 0.0028944 seconds, Stopping threads took: 0.0028351 seconds");
Assert.assertNotNull(data);
Assert.assertEquals(5_042_000_000L, data.timestamp);
Assert.assertEquals( 2_894_400L, data.stopTime);
Assert.assertEquals( 2_835_100L, data.ttspTime);
}
@Test
public void parseJDK8u101_Comma() {
SafepointsProfiler.ParsedData data = SafepointsProfiler.parse(
"5,042: Total time for which application threads were stopped: 0,0028944 seconds, Stopping threads took: 0,0028351 seconds");
Assert.assertNotNull(data);
Assert.assertEquals(5_042_000_000L, data.timestamp);
Assert.assertEquals( 2_894_400L, data.stopTime);
Assert.assertEquals( 2_835_100L, data.ttspTime);
}
@Test
public void parseJDK9b140_Dot() {
SafepointsProfiler.ParsedData data = SafepointsProfiler.parse(
"[71.633s][info][safepoint] Total time for which application threads were stopped: 0.0359611 seconds, Stopping threads took: 0.0000516 seconds");
Assert.assertNotNull(data);
Assert.assertEquals(71_633_000_000L, data.timestamp);
Assert.assertEquals( 35_961_100L, data.stopTime);
Assert.assertEquals( 51_600L, data.ttspTime);
}
@Test
public void parseJDK9b140_Comma() {
SafepointsProfiler.ParsedData data = SafepointsProfiler.parse(
"[71,633s][info][safepoint] Total time for which application threads were stopped: 0,0359611 seconds, Stopping threads took: 0,0000516 seconds");
Assert.assertNotNull(data);
Assert.assertEquals(71_633_000_000L, data.timestamp);
Assert.assertEquals( 35_961_100L, data.stopTime);
Assert.assertEquals( 51_600L, data.ttspTime);
}
@Test
public void parseJDK9b140_Whitespace() {
SafepointsProfiler.ParsedData data = SafepointsProfiler.parse(
"[71,633s][info][safepoint ] Total time for which application threads were stopped: 0,0359611 seconds, Stopping threads took: 0.0000516 seconds");
Assert.assertNotNull(data);
Assert.assertEquals(71_633_000_000L, data.timestamp);
Assert.assertEquals( 35_961_100L, data.stopTime);
Assert.assertEquals( 51_600L, data.ttspTime);
}
}
| 4,690 | 44.543689 | 165 | java |
jmh | jmh-master/jmh-core/src/test/java/org/openjdk/jmh/results/ResultAggregationTest.java | /*
* Copyright (c) 2014, 2014, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package org.openjdk.jmh.results;
import org.junit.Assert;
import org.junit.Test;
import org.openjdk.jmh.util.SampleBuffer;
import java.util.Arrays;
import java.util.concurrent.TimeUnit;
public class ResultAggregationTest {
private static final double ASSERT_ACCURACY = 0.0000001;
@Test
public void testThroughput() {
IterationResult ir = new IterationResult(null, null, null);
ir.addResult(new ThroughputResult(ResultRole.PRIMARY, "", 10_000, 1, TimeUnit.NANOSECONDS));
ir.addResult(new ThroughputResult(ResultRole.PRIMARY, "", 10_000, 1, TimeUnit.NANOSECONDS));
ir.addResult(new ThroughputResult(ResultRole.SECONDARY, "sec", 5_000, 1, TimeUnit.NANOSECONDS));
ir.addResult(new ThroughputResult(ResultRole.SECONDARY, "sec", 5_000, 1, TimeUnit.NANOSECONDS));
Assert.assertEquals(20_000.0, ir.getPrimaryResult().getScore(), ASSERT_ACCURACY);
Assert.assertEquals(10_000.0, ir.getSecondaryResults().get("sec").getScore(), ASSERT_ACCURACY);
Assert.assertEquals(2, ir.getPrimaryResult().getSampleCount());
Assert.assertEquals(2, ir.getSecondaryResults().get("sec").getSampleCount());
Assert.assertEquals(2, ir.getRawPrimaryResults().size());
Assert.assertEquals(2, ir.getRawSecondaryResults().get("sec").size());
BenchmarkResult br = new BenchmarkResult(null, Arrays.asList(ir, ir));
br.addBenchmarkResult(new ThroughputResult(ResultRole.SECONDARY, "bench", 3_000, 1, TimeUnit.NANOSECONDS));
Assert.assertEquals(20_000.0, br.getPrimaryResult().getScore(), ASSERT_ACCURACY);
Assert.assertEquals(10_000.0, br.getSecondaryResults().get("sec").getScore(), ASSERT_ACCURACY);
Assert.assertEquals(3_000.0, br.getSecondaryResults().get("bench").getScore(), ASSERT_ACCURACY);
Assert.assertEquals(2, br.getPrimaryResult().getSampleCount());
Assert.assertEquals(2, br.getSecondaryResults().get("sec").getSampleCount());
Assert.assertEquals(1, br.getSecondaryResults().get("bench").getSampleCount());
Assert.assertEquals(2, br.getIterationResults().size());
RunResult rr = new RunResult(null, Arrays.asList(br, br));
Assert.assertEquals(20_000.0, rr.getPrimaryResult().getScore(), ASSERT_ACCURACY);
Assert.assertEquals(10_000.0, rr.getSecondaryResults().get("sec").getScore(), ASSERT_ACCURACY);
Assert.assertEquals(3_000.0, rr.getSecondaryResults().get("bench").getScore(), ASSERT_ACCURACY);
Assert.assertEquals(4, rr.getPrimaryResult().getSampleCount());
Assert.assertEquals(4, rr.getSecondaryResults().get("sec").getSampleCount());
Assert.assertEquals(2, rr.getSecondaryResults().get("bench").getSampleCount());
Assert.assertEquals(2, rr.getBenchmarkResults().size());
}
@Test
public void testAverageTime() {
IterationResult ir = new IterationResult(null, null, null);
ir.addResult(new AverageTimeResult(ResultRole.PRIMARY, "", 1, 10_000, TimeUnit.NANOSECONDS));
ir.addResult(new AverageTimeResult(ResultRole.PRIMARY, "", 1, 10_000, TimeUnit.NANOSECONDS));
ir.addResult(new AverageTimeResult(ResultRole.SECONDARY, "sec", 1, 5_000, TimeUnit.NANOSECONDS));
ir.addResult(new AverageTimeResult(ResultRole.SECONDARY, "sec", 1, 5_000, TimeUnit.NANOSECONDS));
Assert.assertEquals(10_000.0, ir.getPrimaryResult().getScore(), ASSERT_ACCURACY);
Assert.assertEquals(5_000.0, ir.getSecondaryResults().get("sec").getScore(), ASSERT_ACCURACY);
Assert.assertEquals(2, ir.getPrimaryResult().getSampleCount());
Assert.assertEquals(2, ir.getSecondaryResults().get("sec").getSampleCount());
Assert.assertEquals(2, ir.getRawPrimaryResults().size());
Assert.assertEquals(2, ir.getRawSecondaryResults().get("sec").size());
BenchmarkResult br = new BenchmarkResult(null, Arrays.asList(ir, ir));
br.addBenchmarkResult(new AverageTimeResult(ResultRole.SECONDARY, "bench", 1, 3_000, TimeUnit.NANOSECONDS));
Assert.assertEquals(10_000.0, br.getPrimaryResult().getScore(), ASSERT_ACCURACY);
Assert.assertEquals(5_000.0, br.getSecondaryResults().get("sec").getScore(), ASSERT_ACCURACY);
Assert.assertEquals(3_000.0, br.getSecondaryResults().get("bench").getScore(), ASSERT_ACCURACY);
Assert.assertEquals(2, br.getPrimaryResult().getSampleCount());
Assert.assertEquals(2, br.getSecondaryResults().get("sec").getSampleCount());
Assert.assertEquals(1, br.getSecondaryResults().get("bench").getSampleCount());
Assert.assertEquals(2, br.getIterationResults().size());
RunResult rr = new RunResult(null, Arrays.asList(br, br));
Assert.assertEquals(10_000.0, rr.getPrimaryResult().getScore(), ASSERT_ACCURACY);
Assert.assertEquals(5_000.0, rr.getSecondaryResults().get("sec").getScore(), ASSERT_ACCURACY);
Assert.assertEquals(3_000.0, rr.getSecondaryResults().get("bench").getScore(), ASSERT_ACCURACY);
Assert.assertEquals(4, rr.getPrimaryResult().getSampleCount());
Assert.assertEquals(4, rr.getSecondaryResults().get("sec").getSampleCount());
Assert.assertEquals(2, rr.getSecondaryResults().get("bench").getSampleCount());
Assert.assertEquals(2, rr.getBenchmarkResults().size());
}
@Test
public void testSampleTime() {
SampleBuffer sb10000 = new SampleBuffer();
sb10000.add(10_000);
SampleBuffer sb5000 = new SampleBuffer();
sb5000.add(5_000);
SampleBuffer sb3000 = new SampleBuffer();
sb3000.add(3_000);
IterationResult ir = new IterationResult(null, null, null);
ir.addResult(new SampleTimeResult(ResultRole.PRIMARY, "", sb10000, TimeUnit.NANOSECONDS));
ir.addResult(new SampleTimeResult(ResultRole.PRIMARY, "", sb10000, TimeUnit.NANOSECONDS));
ir.addResult(new SampleTimeResult(ResultRole.SECONDARY, "sec", sb5000, TimeUnit.NANOSECONDS));
ir.addResult(new SampleTimeResult(ResultRole.SECONDARY, "sec", sb5000, TimeUnit.NANOSECONDS));
Assert.assertEquals(10_000.0, ir.getPrimaryResult().getScore(), ASSERT_ACCURACY);
Assert.assertEquals(5_000.0, ir.getSecondaryResults().get("sec").getScore(), ASSERT_ACCURACY);
Assert.assertEquals(2, ir.getRawPrimaryResults().size());
Assert.assertEquals(2, ir.getRawSecondaryResults().get("sec").size());
Assert.assertEquals(2, ir.getPrimaryResult().getSampleCount());
Assert.assertEquals(2, ir.getSecondaryResults().get("sec").getSampleCount());
BenchmarkResult br = new BenchmarkResult(null, Arrays.asList(ir, ir));
br.addBenchmarkResult(new SampleTimeResult(ResultRole.SECONDARY, "bench", sb3000, TimeUnit.NANOSECONDS));
Assert.assertEquals(10_000.0, br.getPrimaryResult().getScore(), ASSERT_ACCURACY);
Assert.assertEquals(5_000.0, br.getSecondaryResults().get("sec").getScore(), ASSERT_ACCURACY);
Assert.assertEquals(3_000.0, br.getSecondaryResults().get("bench").getScore(), ASSERT_ACCURACY);
Assert.assertEquals(4, br.getPrimaryResult().getSampleCount());
Assert.assertEquals(4, br.getSecondaryResults().get("sec").getSampleCount());
Assert.assertEquals(1, br.getSecondaryResults().get("bench").getSampleCount());
Assert.assertEquals(2, br.getIterationResults().size());
RunResult rr = new RunResult(null, Arrays.asList(br, br));
Assert.assertEquals(10_000.0, rr.getPrimaryResult().getScore(), ASSERT_ACCURACY);
Assert.assertEquals(5_000.0, rr.getSecondaryResults().get("sec").getScore(), ASSERT_ACCURACY);
Assert.assertEquals(3_000.0, rr.getSecondaryResults().get("bench").getScore(), ASSERT_ACCURACY);
Assert.assertEquals(8, rr.getPrimaryResult().getSampleCount());
Assert.assertEquals(8, rr.getSecondaryResults().get("sec").getSampleCount());
Assert.assertEquals(2, rr.getSecondaryResults().get("bench").getSampleCount());
Assert.assertEquals(2, rr.getBenchmarkResults().size());
}
@Test
public void testSingleShot() {
IterationResult ir = new IterationResult(null, null, null);
ir.addResult(new SingleShotResult(ResultRole.PRIMARY, "", 10_000, 1, TimeUnit.NANOSECONDS));
ir.addResult(new SingleShotResult(ResultRole.PRIMARY, "", 10_000, 1, TimeUnit.NANOSECONDS));
ir.addResult(new SingleShotResult(ResultRole.SECONDARY, "sec", 5_000, 1, TimeUnit.NANOSECONDS));
ir.addResult(new SingleShotResult(ResultRole.SECONDARY, "sec", 5_000, 1, TimeUnit.NANOSECONDS));
Assert.assertEquals(10_000.0, ir.getPrimaryResult().getScore(), ASSERT_ACCURACY);
Assert.assertEquals(5_000.0, ir.getSecondaryResults().get("sec").getScore(), ASSERT_ACCURACY);
Assert.assertEquals(2, ir.getPrimaryResult().getSampleCount());
Assert.assertEquals(2, ir.getSecondaryResults().get("sec").getSampleCount());
Assert.assertEquals(2, ir.getRawPrimaryResults().size());
Assert.assertEquals(2, ir.getRawSecondaryResults().get("sec").size());
BenchmarkResult br = new BenchmarkResult(null, Arrays.asList(ir, ir));
br.addBenchmarkResult(new SingleShotResult(ResultRole.SECONDARY, "bench", 3_000, 1, TimeUnit.NANOSECONDS));
Assert.assertEquals(10_000.0, br.getPrimaryResult().getScore(), ASSERT_ACCURACY);
Assert.assertEquals(5_000.0, br.getSecondaryResults().get("sec").getScore(), ASSERT_ACCURACY);
Assert.assertEquals(3_000.0, br.getSecondaryResults().get("bench").getScore(), ASSERT_ACCURACY);
Assert.assertEquals(2, br.getPrimaryResult().getSampleCount());
Assert.assertEquals(2, br.getSecondaryResults().get("sec").getSampleCount());
Assert.assertEquals(1, br.getSecondaryResults().get("bench").getSampleCount());
Assert.assertEquals(2, br.getIterationResults().size());
RunResult rr = new RunResult(null, Arrays.asList(br, br));
Assert.assertEquals(10_000.0, rr.getPrimaryResult().getScore(), ASSERT_ACCURACY);
Assert.assertEquals(5_000.0, rr.getSecondaryResults().get("sec").getScore(), ASSERT_ACCURACY);
Assert.assertEquals(3_000.0, rr.getSecondaryResults().get("bench").getScore(), ASSERT_ACCURACY);
Assert.assertEquals(4, rr.getPrimaryResult().getSampleCount());
Assert.assertEquals(4, rr.getSecondaryResults().get("sec").getSampleCount());
Assert.assertEquals(2, rr.getSecondaryResults().get("bench").getSampleCount());
Assert.assertEquals(2, rr.getBenchmarkResults().size());
}
}
| 11,781 | 62.686486 | 116 | java |
jmh | jmh-master/jmh-core/src/test/java/org/openjdk/jmh/results/TestAggregateResult.java | /*
* Copyright (c) 2005, 2013, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package org.openjdk.jmh.results;
import org.junit.BeforeClass;
import org.junit.Test;
import org.openjdk.jmh.annotations.Mode;
import org.openjdk.jmh.infra.BenchmarkParams;
import org.openjdk.jmh.infra.IterationParams;
import org.openjdk.jmh.runner.IterationType;
import org.openjdk.jmh.runner.options.TimeValue;
import org.openjdk.jmh.util.Utils;
import org.openjdk.jmh.util.Version;
import java.util.Collections;
import java.util.concurrent.TimeUnit;
import static org.junit.Assert.assertEquals;
/**
* Tests for AggregateResult
*/
public class TestAggregateResult {
private static IterationResult result;
private static final double[] values = {10.0, 20.0, 30.0, 40.0, 50.0};
@BeforeClass
public static void setupClass() {
result = new IterationResult(
new BenchmarkParams("blah", "blah", false,
1, new int[]{1}, Collections.<String>emptyList(),
1, 1,
new IterationParams(IterationType.WARMUP, 1, TimeValue.seconds(1), 1),
new IterationParams(IterationType.MEASUREMENT, 1, TimeValue.seconds(1), 1),
Mode.Throughput, null, TimeUnit.SECONDS, 1,
Utils.getCurrentJvm(), Collections.<String>emptyList(),
System.getProperty("java.version"), System.getProperty("java.vm.name"), System.getProperty("java.vm.version"), Version.getPlainVersion(),
TimeValue.days(1)),
new IterationParams(IterationType.MEASUREMENT, 1, TimeValue.days(1), 1),
null
);
for (double d : values) {
result.addResult(new ThroughputResult(ResultRole.PRIMARY, "test1", (long) d, 10 * 1000 * 1000, TimeUnit.MILLISECONDS));
}
}
@Test
public void testScore() {
assertEquals(15.0, result.getPrimaryResult().getScore(), 0.00001);
}
@Test
public void testScoreUnit() {
assertEquals((new ThroughputResult(ResultRole.PRIMARY, "test1", 1, 1, TimeUnit.MILLISECONDS)).getScoreUnit(), result.getScoreUnit());
}
}
| 3,333 | 40.160494 | 161 | java |
jmh | jmh-master/jmh-core/src/test/java/org/openjdk/jmh/results/TestAverageTimeResult.java | /*
* Copyright (c) 2005, 2013, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package org.openjdk.jmh.results;
import org.junit.Test;
import java.util.Arrays;
import java.util.concurrent.TimeUnit;
import static org.junit.Assert.assertEquals;
public class TestAverageTimeResult {
private static final double ASSERT_ACCURACY = 0.0000001;
@Test
public void testIterationAggregator1() {
AverageTimeResult r1 = new AverageTimeResult(ResultRole.PRIMARY, "test1", 1_000L, 1_000_000L, TimeUnit.MICROSECONDS);
AverageTimeResult r2 = new AverageTimeResult(ResultRole.PRIMARY, "test1", 1_000L, 2_000_000L, TimeUnit.MICROSECONDS);
Result result = r1.getIterationAggregator().aggregate(Arrays.asList(r1, r2));
assertEquals(1.5, result.getScore(), ASSERT_ACCURACY);
assertEquals("us/op", result.getScoreUnit());
}
@Test
public void testIterationAggregator2() {
AverageTimeResult r1 = new AverageTimeResult(ResultRole.PRIMARY, "test1", 1_000L, 1_000_000L, TimeUnit.MICROSECONDS);
AverageTimeResult r2 = new AverageTimeResult(ResultRole.PRIMARY, "test1", 1_000L, 1_000_000L, TimeUnit.MICROSECONDS);
Result result = r1.getIterationAggregator().aggregate(Arrays.asList(r1, r2));
assertEquals(1.0, result.getScore(), ASSERT_ACCURACY);
assertEquals("us/op", result.getScoreUnit());
}
@Test
public void testThreadAggregator1() {
AverageTimeResult r1 = new AverageTimeResult(ResultRole.PRIMARY, "test1", 1_000L, 1_000_000L, TimeUnit.MICROSECONDS);
AverageTimeResult r2 = new AverageTimeResult(ResultRole.PRIMARY, "test1", 1_000L, 1_000_000L, TimeUnit.MICROSECONDS);
Result result = r1.getThreadAggregator().aggregate(Arrays.asList(r1, r2));
assertEquals(1.0, result.getScore(), ASSERT_ACCURACY);
assertEquals("us/op", result.getScoreUnit());
}
@Test
public void testThreadAggregator2() {
AverageTimeResult r1 = new AverageTimeResult(ResultRole.PRIMARY, "test1", 1_000L, 1_000_000L, TimeUnit.MICROSECONDS);
AverageTimeResult r2 = new AverageTimeResult(ResultRole.PRIMARY, "test1", 1_000L, 2_000_000L, TimeUnit.MICROSECONDS);
Result result = r1.getThreadAggregator().aggregate(Arrays.asList(r1, r2));
assertEquals(1.5, result.getScore(), ASSERT_ACCURACY);
assertEquals("us/op", result.getScoreUnit());
}
}
| 3,542 | 44.423077 | 125 | java |
jmh | jmh-master/jmh-core/src/test/java/org/openjdk/jmh/results/TestBenchmarkResult.java | /*
* Copyright (c) 2014, 2015, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package org.openjdk.jmh.results;
import org.junit.Assert;
import org.junit.Test;
import org.openjdk.jmh.util.ListStatistics;
import java.util.Arrays;
import java.util.Collection;
import java.util.Map;
public class TestBenchmarkResult {
@Test
public void testMissingSecondaries() {
IterationResult ir1 = new IterationResult(null, null, null);
ir1.addResult(new PrimaryResult());
ir1.addResult(new SecondaryResult("label1", 1));
IterationResult ir2 = new IterationResult(null, null, null);
ir2.addResult(new PrimaryResult());
ir2.addResult(new SecondaryResult("label2", 2));
IterationResult ir3 = new IterationResult(null, null, null);
ir3.addResult(new PrimaryResult());
ir3.addResult(new SecondaryResult("label2", 3));
BenchmarkResult br = new BenchmarkResult(null, Arrays.asList(ir1, ir2, ir3));
Map<String, Result> sr = br.getSecondaryResults();
Assert.assertEquals(2, sr.size());
Assert.assertEquals(1.0D, sr.get("label1").getScore(), 0.001);
Assert.assertEquals(5.0D, sr.get("label2").getScore(), 0.001);
}
public static class PrimaryResult extends Result<PrimaryResult> {
public PrimaryResult() {
super(ResultRole.PRIMARY, "Boo", of(1.0D), "unit", AggregationPolicy.SUM);
}
@Override
protected Aggregator<PrimaryResult> getThreadAggregator() {
return new PrimaryResultAggregator();
}
@Override
protected Aggregator<PrimaryResult> getIterationAggregator() {
return new PrimaryResultAggregator();
}
}
public static class SecondaryResult extends Result<SecondaryResult> {
public SecondaryResult(String label, double val) {
super(ResultRole.SECONDARY, label, of(val), "unit", AggregationPolicy.SUM);
}
protected Aggregator<SecondaryResult> getThreadAggregator() {
return new SecondaryResultAggregator();
}
@Override
protected Aggregator<SecondaryResult> getIterationAggregator() {
return new SecondaryResultAggregator();
}
}
public static class PrimaryResultAggregator implements Aggregator<PrimaryResult> {
@Override
public PrimaryResult aggregate(Collection<PrimaryResult> results) {
return new PrimaryResult();
}
}
public static class SecondaryResultAggregator implements Aggregator<SecondaryResult> {
@Override
public SecondaryResult aggregate(Collection<SecondaryResult> results) {
String label = null;
ListStatistics s = new ListStatistics();
for (SecondaryResult r : results) {
if (label == null) {
label = r.getLabel();
} else {
Assert.assertEquals(label, r.getLabel());
}
s.addValue(r.getScore());
}
return new SecondaryResult(label, s.getSum());
}
}
}
| 4,262 | 37.0625 | 90 | java |
jmh | jmh-master/jmh-core/src/test/java/org/openjdk/jmh/results/TestSampleTimeResult.java | /*
* Copyright (c) 2005, 2013, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package org.openjdk.jmh.results;
import org.junit.Test;
import org.openjdk.jmh.util.SampleBuffer;
import java.util.Arrays;
import java.util.concurrent.TimeUnit;
import static org.junit.Assert.assertEquals;
public class TestSampleTimeResult {
private static final double ASSERT_ACCURACY = 0.0000001;
@Test
public void testIterationAggregator1() {
SampleBuffer b1 = new SampleBuffer();
b1.add(1000);
b1.add(2000);
SampleBuffer b2 = new SampleBuffer();
b2.add(3000);
b2.add(4000);
SampleTimeResult r1 = new SampleTimeResult(ResultRole.PRIMARY, "Test1", b1, TimeUnit.MICROSECONDS);
SampleTimeResult r2 = new SampleTimeResult(ResultRole.PRIMARY, "Test1", b2, TimeUnit.MICROSECONDS);
Result result = r1.getIterationAggregator().aggregate(Arrays.asList(r1, r2));
assertEquals(2.5, result.getScore(), ASSERT_ACCURACY);
assertEquals("us/op", result.getScoreUnit());
}
@Test
public void testThreadAggregator1() {
SampleBuffer b1 = new SampleBuffer();
b1.add(1000);
b1.add(2000);
SampleBuffer b2 = new SampleBuffer();
b2.add(3000);
b2.add(4000);
SampleTimeResult r1 = new SampleTimeResult(ResultRole.PRIMARY, "Test1", b1, TimeUnit.MICROSECONDS);
SampleTimeResult r2 = new SampleTimeResult(ResultRole.PRIMARY, "Test1", b2, TimeUnit.MICROSECONDS);
Result result = r1.getThreadAggregator().aggregate(Arrays.asList(r1, r2));
assertEquals(2.5, result.getScore(), ASSERT_ACCURACY);
assertEquals("us/op", result.getScoreUnit());
}
}
| 2,846 | 36.460526 | 107 | java |
jmh | jmh-master/jmh-core/src/test/java/org/openjdk/jmh/results/TestSingleShotResult.java | /*
* Copyright (c) 2005, 2013, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package org.openjdk.jmh.results;
import org.junit.Test;
import java.util.Arrays;
import java.util.concurrent.TimeUnit;
import static org.junit.Assert.assertEquals;
public class TestSingleShotResult {
private static final double ASSERT_ACCURACY = 0.0000001;
@Test
public void testIterationAggregator1() {
SingleShotResult r1 = new SingleShotResult(ResultRole.PRIMARY, "Test1", 1000L, 1, TimeUnit.MICROSECONDS);
SingleShotResult r2 = new SingleShotResult(ResultRole.PRIMARY, "Test1", 2000L, 1, TimeUnit.MICROSECONDS);
Result result = r1.getIterationAggregator().aggregate(Arrays.asList(r1, r2));
assertEquals(1.5, result.getScore(), ASSERT_ACCURACY);
assertEquals("us/op", result.getScoreUnit());
}
@Test
public void testThreadAggregator1() {
SingleShotResult r1 = new SingleShotResult(ResultRole.PRIMARY, "Test1", 1000L, 1, TimeUnit.MICROSECONDS);
SingleShotResult r2 = new SingleShotResult(ResultRole.PRIMARY, "Test1", 2000L, 1, TimeUnit.MICROSECONDS);
Result result = r1.getThreadAggregator().aggregate(Arrays.asList(r1, r2));
assertEquals(1.5, result.getScore(), ASSERT_ACCURACY);
assertEquals("us/op", result.getScoreUnit());
}
@Test
public void testMultiops() {
SingleShotResult r1 = new SingleShotResult(ResultRole.PRIMARY, "Test1", 1000L, 1, TimeUnit.MICROSECONDS);
SingleShotResult r2 = new SingleShotResult(ResultRole.PRIMARY, "Test1", 1000L, 2, TimeUnit.MICROSECONDS);
assertEquals(1, r1.getScore(), ASSERT_ACCURACY);
assertEquals(0.5, r2.getScore(), ASSERT_ACCURACY);
}
}
| 2,859 | 41.058824 | 113 | java |
jmh | jmh-master/jmh-core/src/test/java/org/openjdk/jmh/results/TestThroughputResult.java | /*
* Copyright (c) 2005, 2013, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package org.openjdk.jmh.results;
import org.junit.Test;
import java.util.Arrays;
import java.util.concurrent.TimeUnit;
import static org.junit.Assert.assertEquals;
public class TestThroughputResult {
private static final double ASSERT_ACCURACY = 0.0000001;
/**
* Test of getScore method, of class ThroughputResult.
*/
@Test
public void testGetScore() {
ThroughputResult instance = new ThroughputResult(ResultRole.PRIMARY, "test1", 1_000L, 1_000_000L, TimeUnit.MILLISECONDS);
assertEquals(1_000, instance.getScore(), 0.0);
ThroughputResult instance2 = new ThroughputResult(ResultRole.PRIMARY, "test1", 1_000L, 1_000_000L, TimeUnit.SECONDS);
assertEquals(1_000_000, instance2.getScore(), 0.0);
ThroughputResult instance3 = new ThroughputResult(ResultRole.PRIMARY, "test1", 1_000L, 1_000L, TimeUnit.MILLISECONDS);
assertEquals(1_000 / (1_000 / (double) 1_000_000), instance3.getScore(), 0.0);
}
@Test
public void testTimeUnits() {
ThroughputResult instanced = new ThroughputResult(ResultRole.PRIMARY, "test1", 1_000L, 1_000_000L, TimeUnit.DAYS);
assertEquals(86_400_000_000D, instanced.getScore(), 0.0);
assertEquals("ops/day", instanced.getScoreUnit());
ThroughputResult instanceh = new ThroughputResult(ResultRole.PRIMARY, "test1", 1_000L, 1_000_000L, TimeUnit.HOURS);
assertEquals(3_600_000_000D, instanceh.getScore(), 0.0);
assertEquals("ops/hr", instanceh.getScoreUnit());
ThroughputResult instancem = new ThroughputResult(ResultRole.PRIMARY, "test1", 1_000L, 1_000_000L, TimeUnit.MINUTES);
assertEquals(60_000_000, instancem.getScore(), 0.0);
assertEquals("ops/min", instancem.getScoreUnit());
ThroughputResult instance = new ThroughputResult(ResultRole.PRIMARY, "test1", 1_000L, 1_000_000L, TimeUnit.SECONDS);
assertEquals(1_000_000, instance.getScore(), 0.0);
assertEquals("ops/s", instance.getScoreUnit());
ThroughputResult instance2 = new ThroughputResult(ResultRole.PRIMARY, "test1", 1_000L, 1_000_000L, TimeUnit.MILLISECONDS);
assertEquals(1_000, instance2.getScore(), 0.0);
assertEquals("ops/ms", instance2.getScoreUnit());
ThroughputResult instance3 = new ThroughputResult(ResultRole.PRIMARY, "test1", 1_000L, 1_000_000L, TimeUnit.MICROSECONDS);
assertEquals(1, instance3.getScore(), 0.0);
assertEquals("ops/us", instance3.getScoreUnit());
ThroughputResult instance4 = new ThroughputResult(ResultRole.PRIMARY, "test1", 1_000L, 1_000_000L, TimeUnit.NANOSECONDS);
assertEquals(0.001, instance4.getScore(), 0.0);
assertEquals("ops/ns", instance4.getScoreUnit());
}
@Test
public void testRunAggregator1() {
ThroughputResult r1 = new ThroughputResult(ResultRole.PRIMARY, "test1", 1_000L, 10_000_000L, TimeUnit.MILLISECONDS);
ThroughputResult r2 = new ThroughputResult(ResultRole.PRIMARY, "test1", 2_000L, 10_000_000L, TimeUnit.MILLISECONDS);
Result result = r1.getIterationAggregator().aggregate(Arrays.asList(r1, r2));
assertEquals(150.0, result.getScore(), ASSERT_ACCURACY);
assertEquals("ops/ms", result.getScoreUnit());
}
@Test
public void testRunAggregator2() {
ThroughputResult r1 = new ThroughputResult(ResultRole.PRIMARY, "test1", 1_000L, 10_000_000L, TimeUnit.MILLISECONDS);
ThroughputResult r2 = new ThroughputResult(ResultRole.PRIMARY, "test1", 2_000L, 20_000_000L, TimeUnit.MILLISECONDS);
Result result = r1.getIterationAggregator().aggregate(Arrays.asList(r1, r2));
assertEquals(100.0, result.getScore(), ASSERT_ACCURACY);
assertEquals("ops/ms", result.getScoreUnit());
}
@Test // regression test, check for overflow
public void testIterationAggregator3() {
ThroughputResult r1 = new ThroughputResult(ResultRole.PRIMARY, "test1", 1_000_000_000L, 10_000_000L, TimeUnit.MILLISECONDS);
ThroughputResult r2 = new ThroughputResult(ResultRole.PRIMARY, "test1", 2_000_000_000L, 20_000_000L, TimeUnit.MILLISECONDS);
Result result = r1.getIterationAggregator().aggregate(Arrays.asList(r1, r2));
assertEquals(100_000_000.0, result.getScore(), ASSERT_ACCURACY);
assertEquals("ops/ms", result.getScoreUnit());
}
@Test
public void testThreadAggregator1() {
ThroughputResult r1 = new ThroughputResult(ResultRole.PRIMARY, "test1", 1_000L, 10_000_000L, TimeUnit.MILLISECONDS);
ThroughputResult r2 = new ThroughputResult(ResultRole.PRIMARY, "test1", 2_000L, 10_000_000L, TimeUnit.MILLISECONDS);
Result result = r1.getThreadAggregator().aggregate(Arrays.asList(r1, r2));
assertEquals("ops/ms", result.getScoreUnit());
assertEquals(300.0, result.getScore(), ASSERT_ACCURACY);
}
@Test
public void testThreadAggregator2() {
ThroughputResult r1 = new ThroughputResult(ResultRole.PRIMARY, "test1", 1_000L, 10_000_000L, TimeUnit.MILLISECONDS);
ThroughputResult r2 = new ThroughputResult(ResultRole.PRIMARY, "test1", 2_000L, 20_000_000L, TimeUnit.MILLISECONDS);
Result result = r1.getThreadAggregator().aggregate(Arrays.asList(r1, r2));
assertEquals("ops/ms", result.getScoreUnit());
assertEquals(200.0, result.getScore(), ASSERT_ACCURACY);
}
@Test // regression test, check for overflow
public void testThreadAggregator3() {
ThroughputResult r1 = new ThroughputResult(ResultRole.PRIMARY, "test1", 1_000_000_000L, 10_000_000L, TimeUnit.MILLISECONDS);
ThroughputResult r2 = new ThroughputResult(ResultRole.PRIMARY, "test1", 2_000_000_000L, 20_000_000L, TimeUnit.MILLISECONDS);
Result result = r1.getThreadAggregator().aggregate(Arrays.asList(r1, r2));
assertEquals("ops/ms", result.getScoreUnit());
assertEquals(200_000_000.0, result.getScore(), ASSERT_ACCURACY);
}
}
| 7,170 | 49.5 | 132 | java |
jmh | jmh-master/jmh-core/src/test/java/org/openjdk/jmh/results/format/JSONResultFormatTest.java | /*
* Copyright (c) 2014, 2015, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package org.openjdk.jmh.results.format;
import org.junit.Test;
import static org.junit.Assert.*;
/**
* Extra tests for special cases of the JSON formatter.
*
* @author Jens Wilke
* @see JSONResultFormat
*/
public class JSONResultFormatTest {
@Test
public void toJsonString_tidy() {
String s = JSONResultFormat.toJsonString("abc,\"{}()\\(\\)[]{}");
s = JSONResultFormat.tidy(s);
assertEquals("\"abc,\\\"{}()\\\\(\\\\)[]{}\"\n", s);
}
@Test
public void toJsonString_tidy_curly() {
String s = JSONResultFormat.toJsonString("{}");
s = JSONResultFormat.tidy(s);
assertEquals("\"{}\"\n", s);
}
@Test
public void toJsonString_tidy_curved() {
String s = JSONResultFormat.toJsonString("()");
s = JSONResultFormat.tidy(s);
assertEquals("\"()\"\n", s);
}
@Test
public void toJsonString_tidy_escapedDoubleQuote() {
String s = JSONResultFormat.toJsonString("\"");
s = JSONResultFormat.tidy(s);
assertEquals("\"\\\"\"\n", s);
}
@Test
public void toJsonString_tidy_escapedEscape() {
String s = JSONResultFormat.toJsonString("\\");
s = JSONResultFormat.tidy(s);
assertEquals("\"\\\\\"\n", s);
}
/**
* Check that every ASCII character in a string makes it transparently through
* the JSON tidying and formatting process.
*/
@Test
public void toJsonString_tidy_asciiTransparent () {
for (char i = 32; i < 127; i++) {
if (i == '"') {
continue;
}
if (i == '\\') {
continue;
}
String s = JSONResultFormat.toJsonString(Character.toString(i));
s = JSONResultFormat.tidy(s);
assertEquals("\"" + i + "\"\n", s);
}
}
} | 3,063 | 31.946237 | 82 | java |
jmh | jmh-master/jmh-core/src/test/java/org/openjdk/jmh/results/format/ResultFormatTest.java | /*
* Copyright (c) 2005, 2013, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package org.openjdk.jmh.results.format;
import org.junit.Assert;
import org.junit.Test;
import org.openjdk.jmh.annotations.Mode;
import org.openjdk.jmh.infra.BenchmarkParams;
import org.openjdk.jmh.infra.IterationParams;
import org.openjdk.jmh.results.*;
import org.openjdk.jmh.runner.IterationType;
import org.openjdk.jmh.runner.WorkloadParams;
import org.openjdk.jmh.runner.options.TimeValue;
import org.openjdk.jmh.util.FileUtils;
import org.openjdk.jmh.util.Utils;
import java.io.*;
import java.util.*;
import java.util.concurrent.TimeUnit;
/**
* These tests seal the machine-readable format.
* Any change to these tests should be discussed with the maintainers first!
*/
public class ResultFormatTest {
/**
* Use constant dummy for JVM instead of current JVM to compare with golden file.
*/
private static final String JVM_DUMMY = "javadummy";
/**
* Use constant dummy for JVM instead of current JVM to compare with golden file.
*/
private static final String JDK_VERSION_DUMMY = "1.8-dummy";
private static final String VM_NAME_DUMMY = "DummyVM";
private static final String VM_VERSION_DUMMY = "4711";
private static final String JMH_VERSION_DUMMY = "1.18";
private Collection<RunResult> getStub() {
Collection<RunResult> results = new TreeSet<>(RunResult.DEFAULT_SORT_COMPARATOR);
Random r = new Random(12345);
Random ar = new Random(12345);
for (int b = 0; b < r.nextInt(10); b++) {
WorkloadParams ps = new WorkloadParams();
ps.put("param0", "value0", 0);
ps.put("param1", "[value1]", 1);
ps.put("param2", "{value2}", 2);
ps.put("param3", "'value3'", 3);
ps.put("param4", "\"value4\"", 4);
BenchmarkParams params = new BenchmarkParams(
"benchmark_" + b,
JSONResultFormat.class.getName() + ".benchmark_" + b + "_" + Mode.Throughput,
false,
r.nextInt(1000),
new int[]{ r.nextInt(1000) },
Collections.<String>emptyList(),
r.nextInt(1000),
r.nextInt(1000),
new IterationParams(IterationType.WARMUP, r.nextInt(1000), TimeValue.seconds(r.nextInt(1000)), 1),
new IterationParams(IterationType.MEASUREMENT, r.nextInt(1000), TimeValue.seconds(r.nextInt(1000)), 1),
Mode.Throughput,
ps,
TimeUnit.SECONDS, 1,
JVM_DUMMY,
Collections.<String>emptyList(),
JDK_VERSION_DUMMY, VM_NAME_DUMMY, VM_VERSION_DUMMY, JMH_VERSION_DUMMY,
TimeValue.days(1));
Collection<BenchmarkResult> benchmarkResults = new ArrayList<>();
for (int f = 0; f < r.nextInt(10); f++) {
Collection<IterationResult> iterResults = new ArrayList<>();
for (int c = 0; c < r.nextInt(10); c++) {
IterationResult res = new IterationResult(params, params.getMeasurement(), null);
res.addResult(new ThroughputResult(ResultRole.PRIMARY, "test", r.nextInt(1000), 1000 * 1000, TimeUnit.MILLISECONDS));
res.addResult(new ThroughputResult(ResultRole.SECONDARY, "secondary1", r.nextInt(1000), 1000 * 1000, TimeUnit.MILLISECONDS));
res.addResult(new ThroughputResult(ResultRole.SECONDARY, "secondary2", r.nextInt(1000), 1000 * 1000, TimeUnit.MILLISECONDS));
if (ar.nextBoolean()) {
res.addResult(new ThroughputResult(ResultRole.SECONDARY, "secondary3", ar.nextInt(1000), 1000 * 1000, TimeUnit.MILLISECONDS));
}
iterResults.add(res);
}
benchmarkResults.add(new BenchmarkResult(params, iterResults));
}
results.add(new RunResult(params, benchmarkResults));
}
return results;
}
private void compare(String actualFile, String goldenFile) throws IOException {
BufferedReader actualReader = new BufferedReader(new FileReader(actualFile));
BufferedReader goldenReader = new BufferedReader(new InputStreamReader(ResultFormatTest.class.getResourceAsStream("/org/openjdk/jmh/results/format/" + goldenFile)));
String actualLines = Utils.join(FileUtils.readAllLines(actualReader), "\n");
String goldenLines = Utils.join(FileUtils.readAllLines(goldenReader), "\n");
Assert.assertEquals("Mismatch", goldenLines, actualLines);
}
public void test(ResultFormatType type, Locale locale, String suffix) throws IOException {
Locale prevLocale = Locale.getDefault();
Locale.setDefault(locale);
String actualFileName = "test." + type.toString().toLowerCase() + suffix;
String goldenFileName = "output-golden." + type.toString().toLowerCase() + suffix;
try {
String actualFile = FileUtils.tempFile(actualFileName).getAbsolutePath();
ResultFormatFactory.getInstance(type, actualFile).writeOut(getStub());
compare(actualFile, goldenFileName);
PrintStream ps = new PrintStream(actualFile, "UTF-8");
ResultFormatFactory.getInstance(type, ps).writeOut(getStub());
ps.close();
compare(actualFile, goldenFileName);
} finally {
Locale.setDefault(prevLocale);
}
}
/*
* JSON has a strict format for numbers, the results should be Locale-agnostic.
*/
@Test
public void jsonTest_ROOT() throws IOException {
test(ResultFormatType.JSON, Locale.ROOT, "");
}
@Test
public void jsonTest_US() throws IOException {
test(ResultFormatType.JSON, Locale.US, "");
}
@Test
public void jsonTest_RU() throws IOException {
test(ResultFormatType.JSON, new Locale("RU"), "");
}
/*
* CSV and SCSV data should conform to the Locale.
*/
@Test
public void csvTest_ROOT() throws IOException {
test(ResultFormatType.CSV, Locale.ROOT, ".root");
}
@Test
public void csvTest_US() throws IOException {
test(ResultFormatType.CSV, Locale.US, ".us");
}
@Test
public void csvTest_RU() throws IOException {
test(ResultFormatType.CSV, new Locale("RU"), ".ru");
}
@Test
public void scsvTest_ROOT() throws IOException {
test(ResultFormatType.SCSV, Locale.ROOT, ".root");
}
@Test
public void scsvTest_US() throws IOException {
test(ResultFormatType.SCSV, Locale.US, ".us");
}
@Test
public void scsvTest_RU() throws IOException {
test(ResultFormatType.SCSV, new Locale("RU"), ".ru");
}
/*
* LaTeX output should conform to the Locale.
*/
@Test
public void latexTest_ROOT() throws IOException {
test(ResultFormatType.LATEX, Locale.ROOT, ".root");
}
@Test
public void latexTest_US() throws IOException {
test(ResultFormatType.LATEX, Locale.US, ".us");
}
@Test
public void latexTest_RU() throws IOException {
test(ResultFormatType.LATEX, new Locale("RU"), ".ru");
}
/*
* Text output should conform to the Locale.
*/
@Test
public void textTest_ROOT() throws IOException {
test(ResultFormatType.TEXT, Locale.ROOT, ".root");
}
@Test
public void textTest_US() throws IOException {
test(ResultFormatType.TEXT, Locale.US, ".us");
}
@Test
public void textTest_RU() throws IOException {
test(ResultFormatType.TEXT, new Locale("RU"), ".ru");
}
}
| 8,943 | 36.422594 | 173 | java |
jmh | jmh-master/jmh-core/src/test/java/org/openjdk/jmh/runner/CompilerHintsTest.java | /*
* Copyright (c) 2005, 2014, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package org.openjdk.jmh.runner;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import java.util.ArrayList;
import java.util.List;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
public class CompilerHintsTest {
private String vmName;
@Before
public void storeCurrentVM() {
vmName = System.getProperty("java.vm.name");
}
@Test
public void testListNotEmptyForCompliantJvms() {
for (String name : CompilerHints.HINT_COMPATIBLE_JVMS) {
System.setProperty("java.vm.name", name);
CompilerHints.resetCompilerHintsSelect();
List<String> args = new ArrayList<>();
CompilerHints.addCompilerHints(args);
assertFalse(args.isEmpty());
}
}
@Test
public void testListEmptyForOldZingJvms() {
System.setProperty("java.vm.name", "Zing");
System.setProperty("java.version", "1.7.0-zing_5.9.2.0");
CompilerHints.resetCompilerHintsSelect();
// load up some default hints
List<String> args = new ArrayList<>();
CompilerHints.addCompilerHints(args);
assertTrue(args.isEmpty());
}
@Test
public void testListNotEmptyForNewerZingJvms() {
System.setProperty("java.vm.name", "Zing");
System.setProperty("java.version", "1.7.0-zing_5.10.2.0");
CompilerHints.resetCompilerHintsSelect();
// load up some default hints
List<String> args = new ArrayList<>();
CompilerHints.addCompilerHints(args);
assertFalse(args.isEmpty());
}
@Test
public void testListEmptyForNonCompliantJvms() {
System.setProperty("java.vm.name", "StupidVmCantTakeAHint");
CompilerHints.resetCompilerHintsSelect();
List<String> args = new ArrayList<>();
CompilerHints.addCompilerHints(args);
assertTrue(args.isEmpty());
}
@After
public void restoreCurrentVM() {
System.setProperty("java.vm.name", vmName);
CompilerHints.resetCompilerHintsSelect();
}
}
| 3,306 | 34.180851 | 79 | java |
jmh | jmh-master/jmh-core/src/test/java/org/openjdk/jmh/runner/DistributeGroupsTest.java | /*
* Copyright (c) 2014, 2014, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package org.openjdk.jmh.runner;
import org.junit.Assert;
import org.junit.Test;
import org.openjdk.jmh.infra.ThreadParams;
import java.util.List;
public class DistributeGroupsTest {
@Test
public void test1() {
List<ThreadParams> controls = BenchmarkHandler.distributeThreads(1, new int[]{1});
Assert.assertEquals(1, controls.size());
// threads agree on thread count, and enumerated
Assert.assertEquals(1, controls.get(0).getThreadCount());
Assert.assertEquals(0, controls.get(0).getThreadIndex());
// one group with a single thread
Assert.assertEquals(1, controls.get(0).getGroupCount());
Assert.assertEquals(0, controls.get(0).getGroupIndex());
// the thread is alone in the group
Assert.assertEquals(1, controls.get(0).getGroupThreadCount());
Assert.assertEquals(0, controls.get(0).getGroupThreadIndex());
// no subgroups in the group
Assert.assertEquals(1, controls.get(0).getSubgroupCount());
Assert.assertEquals(0, controls.get(0).getSubgroupIndex());
// the thread is alone in the subgroup
Assert.assertEquals(1, controls.get(0).getSubgroupThreadCount());
Assert.assertEquals(0, controls.get(0).getSubgroupThreadIndex());
}
@Test
public void test2() {
List<ThreadParams> controls = BenchmarkHandler.distributeThreads(2, new int[]{1});
Assert.assertEquals(2, controls.size());
// threads agree on thread count, and enumerated
Assert.assertEquals(2, controls.get(0).getThreadCount());
Assert.assertEquals(2, controls.get(1).getThreadCount());
Assert.assertEquals(0, controls.get(0).getThreadIndex());
Assert.assertEquals(1, controls.get(1).getThreadIndex());
// two groups, each for a single thread
Assert.assertEquals(2, controls.get(0).getGroupCount());
Assert.assertEquals(2, controls.get(1).getGroupCount());
Assert.assertEquals(0, controls.get(0).getGroupIndex());
Assert.assertEquals(1, controls.get(1).getGroupIndex());
// each thread is alone in the group
Assert.assertEquals(1, controls.get(0).getGroupThreadCount());
Assert.assertEquals(1, controls.get(1).getGroupThreadCount());
Assert.assertEquals(0, controls.get(0).getGroupThreadIndex());
Assert.assertEquals(0, controls.get(1).getGroupThreadIndex());
// no subgroups in the group
Assert.assertEquals(1, controls.get(0).getSubgroupCount());
Assert.assertEquals(1, controls.get(1).getSubgroupCount());
Assert.assertEquals(0, controls.get(0).getSubgroupIndex());
Assert.assertEquals(0, controls.get(1).getSubgroupIndex());
// each thread is alone in the subgroup
Assert.assertEquals(1, controls.get(0).getSubgroupThreadCount());
Assert.assertEquals(1, controls.get(1).getSubgroupThreadCount());
Assert.assertEquals(0, controls.get(0).getSubgroupThreadIndex());
Assert.assertEquals(0, controls.get(1).getSubgroupThreadIndex());
}
@Test
public void test3() {
// First "subgroup" is ignored
List<ThreadParams> controls = BenchmarkHandler.distributeThreads(2, new int[]{0, 1});
Assert.assertEquals(2, controls.size());
// threads agree on thread count, and enumerated
Assert.assertEquals(2, controls.get(0).getThreadCount());
Assert.assertEquals(2, controls.get(1).getThreadCount());
Assert.assertEquals(0, controls.get(0).getThreadIndex());
Assert.assertEquals(1, controls.get(1).getThreadIndex());
// two groups, each for a single thread
Assert.assertEquals(2, controls.get(0).getGroupCount());
Assert.assertEquals(2, controls.get(1).getGroupCount());
Assert.assertEquals(0, controls.get(0).getGroupIndex());
Assert.assertEquals(1, controls.get(1).getGroupIndex());
// each thread is alone in the group
Assert.assertEquals(1, controls.get(0).getGroupThreadCount());
Assert.assertEquals(1, controls.get(1).getGroupThreadCount());
Assert.assertEquals(0, controls.get(0).getGroupThreadIndex());
Assert.assertEquals(0, controls.get(1).getGroupThreadIndex());
// two subgroups, but first is not populated
Assert.assertEquals(2, controls.get(0).getSubgroupCount());
Assert.assertEquals(2, controls.get(1).getSubgroupCount());
Assert.assertEquals(1, controls.get(0).getSubgroupIndex());
Assert.assertEquals(1, controls.get(1).getSubgroupIndex());
// each thread is alone in the subgroup
Assert.assertEquals(1, controls.get(0).getSubgroupThreadCount());
Assert.assertEquals(1, controls.get(1).getSubgroupThreadCount());
Assert.assertEquals(0, controls.get(0).getSubgroupThreadIndex());
Assert.assertEquals(0, controls.get(1).getSubgroupThreadIndex());
}
@Test
public void test4() {
List<ThreadParams> controls = BenchmarkHandler.distributeThreads(2, new int[]{1, 1});
Assert.assertEquals(2, controls.size());
// threads agree on thread count, and enumerated
Assert.assertEquals(2, controls.get(0).getThreadCount());
Assert.assertEquals(2, controls.get(1).getThreadCount());
Assert.assertEquals(0, controls.get(0).getThreadIndex());
Assert.assertEquals(1, controls.get(1).getThreadIndex());
// one group only
Assert.assertEquals(1, controls.get(0).getGroupCount());
Assert.assertEquals(1, controls.get(1).getGroupCount());
Assert.assertEquals(0, controls.get(0).getGroupIndex());
Assert.assertEquals(0, controls.get(1).getGroupIndex());
// both threads share the group
Assert.assertEquals(2, controls.get(0).getGroupThreadCount());
Assert.assertEquals(2, controls.get(1).getGroupThreadCount());
Assert.assertEquals(0, controls.get(0).getGroupThreadIndex());
Assert.assertEquals(1, controls.get(1).getGroupThreadIndex());
// two subgroups, threads in different subgroups
Assert.assertEquals(2, controls.get(0).getSubgroupCount());
Assert.assertEquals(2, controls.get(1).getSubgroupCount());
Assert.assertEquals(0, controls.get(0).getSubgroupIndex());
Assert.assertEquals(1, controls.get(1).getSubgroupIndex());
// each subgroup has a single thread
Assert.assertEquals(1, controls.get(0).getSubgroupThreadCount());
Assert.assertEquals(1, controls.get(1).getSubgroupThreadCount());
Assert.assertEquals(0, controls.get(0).getSubgroupThreadIndex());
Assert.assertEquals(0, controls.get(1).getSubgroupThreadIndex());
}
@Test
public void test5() {
List<ThreadParams> controls = BenchmarkHandler.distributeThreads(3, new int[]{1, 2});
Assert.assertEquals(3, controls.size());
// threads agree on thread count, and enumerated
Assert.assertEquals(3, controls.get(0).getThreadCount());
Assert.assertEquals(3, controls.get(1).getThreadCount());
Assert.assertEquals(3, controls.get(2).getThreadCount());
Assert.assertEquals(0, controls.get(0).getThreadIndex());
Assert.assertEquals(1, controls.get(1).getThreadIndex());
Assert.assertEquals(2, controls.get(2).getThreadIndex());
// one group only
Assert.assertEquals(1, controls.get(0).getGroupCount());
Assert.assertEquals(1, controls.get(1).getGroupCount());
Assert.assertEquals(1, controls.get(2).getGroupCount());
Assert.assertEquals(0, controls.get(0).getGroupIndex());
Assert.assertEquals(0, controls.get(1).getGroupIndex());
Assert.assertEquals(0, controls.get(2).getGroupIndex());
// all threads share the group
Assert.assertEquals(3, controls.get(0).getGroupThreadCount());
Assert.assertEquals(3, controls.get(1).getGroupThreadCount());
Assert.assertEquals(3, controls.get(2).getGroupThreadCount());
Assert.assertEquals(0, controls.get(0).getGroupThreadIndex());
Assert.assertEquals(1, controls.get(1).getGroupThreadIndex());
Assert.assertEquals(2, controls.get(2).getGroupThreadIndex());
// two subgroups, first thread in distinct subgroup
Assert.assertEquals(2, controls.get(0).getSubgroupCount());
Assert.assertEquals(2, controls.get(1).getSubgroupCount());
Assert.assertEquals(2, controls.get(2).getSubgroupCount());
Assert.assertEquals(0, controls.get(0).getSubgroupIndex());
Assert.assertEquals(1, controls.get(1).getSubgroupIndex());
Assert.assertEquals(1, controls.get(2).getSubgroupIndex());
// first subgroup has a single thread, second has two threads
Assert.assertEquals(1, controls.get(0).getSubgroupThreadCount());
Assert.assertEquals(2, controls.get(1).getSubgroupThreadCount());
Assert.assertEquals(2, controls.get(2).getSubgroupThreadCount());
Assert.assertEquals(0, controls.get(0).getSubgroupThreadIndex());
Assert.assertEquals(0, controls.get(1).getSubgroupThreadIndex());
Assert.assertEquals(1, controls.get(2).getSubgroupThreadIndex());
}
@Test
public void test6() {
List<ThreadParams> controls = BenchmarkHandler.distributeThreads(6, new int[]{1, 2});
Assert.assertEquals(6, controls.size());
// threads agree on thread count, and enumerated
Assert.assertEquals(6, controls.get(0).getThreadCount());
Assert.assertEquals(6, controls.get(1).getThreadCount());
Assert.assertEquals(6, controls.get(2).getThreadCount());
Assert.assertEquals(6, controls.get(3).getThreadCount());
Assert.assertEquals(6, controls.get(4).getThreadCount());
Assert.assertEquals(6, controls.get(5).getThreadCount());
Assert.assertEquals(0, controls.get(0).getThreadIndex());
Assert.assertEquals(1, controls.get(1).getThreadIndex());
Assert.assertEquals(2, controls.get(2).getThreadIndex());
Assert.assertEquals(3, controls.get(3).getThreadIndex());
Assert.assertEquals(4, controls.get(4).getThreadIndex());
Assert.assertEquals(5, controls.get(5).getThreadIndex());
// two groups
Assert.assertEquals(2, controls.get(0).getGroupCount());
Assert.assertEquals(2, controls.get(1).getGroupCount());
Assert.assertEquals(2, controls.get(2).getGroupCount());
Assert.assertEquals(2, controls.get(3).getGroupCount());
Assert.assertEquals(2, controls.get(4).getGroupCount());
Assert.assertEquals(2, controls.get(5).getGroupCount());
Assert.assertEquals(0, controls.get(0).getGroupIndex());
Assert.assertEquals(0, controls.get(1).getGroupIndex());
Assert.assertEquals(0, controls.get(2).getGroupIndex());
Assert.assertEquals(1, controls.get(3).getGroupIndex());
Assert.assertEquals(1, controls.get(4).getGroupIndex());
Assert.assertEquals(1, controls.get(5).getGroupIndex());
// two groups, three threads each
Assert.assertEquals(3, controls.get(0).getGroupThreadCount());
Assert.assertEquals(3, controls.get(1).getGroupThreadCount());
Assert.assertEquals(3, controls.get(2).getGroupThreadCount());
Assert.assertEquals(3, controls.get(3).getGroupThreadCount());
Assert.assertEquals(3, controls.get(4).getGroupThreadCount());
Assert.assertEquals(3, controls.get(5).getGroupThreadCount());
Assert.assertEquals(0, controls.get(0).getGroupThreadIndex());
Assert.assertEquals(1, controls.get(1).getGroupThreadIndex());
Assert.assertEquals(2, controls.get(2).getGroupThreadIndex());
Assert.assertEquals(0, controls.get(3).getGroupThreadIndex());
Assert.assertEquals(1, controls.get(4).getGroupThreadIndex());
Assert.assertEquals(2, controls.get(5).getGroupThreadIndex());
// two subgroups: first subgroup has a single thread, second has two threads
Assert.assertEquals(2, controls.get(0).getSubgroupCount());
Assert.assertEquals(2, controls.get(1).getSubgroupCount());
Assert.assertEquals(2, controls.get(2).getSubgroupCount());
Assert.assertEquals(2, controls.get(3).getSubgroupCount());
Assert.assertEquals(2, controls.get(4).getSubgroupCount());
Assert.assertEquals(2, controls.get(5).getSubgroupCount());
Assert.assertEquals(0, controls.get(0).getSubgroupIndex());
Assert.assertEquals(1, controls.get(1).getSubgroupIndex());
Assert.assertEquals(1, controls.get(2).getSubgroupIndex());
Assert.assertEquals(0, controls.get(3).getSubgroupIndex());
Assert.assertEquals(1, controls.get(4).getSubgroupIndex());
Assert.assertEquals(1, controls.get(5).getSubgroupIndex());
// first subgroup has a single thread, second has two threads
Assert.assertEquals(1, controls.get(0).getSubgroupThreadCount());
Assert.assertEquals(2, controls.get(1).getSubgroupThreadCount());
Assert.assertEquals(2, controls.get(2).getSubgroupThreadCount());
Assert.assertEquals(0, controls.get(3).getSubgroupThreadIndex());
Assert.assertEquals(0, controls.get(4).getSubgroupThreadIndex());
Assert.assertEquals(1, controls.get(5).getSubgroupThreadIndex());
Assert.assertEquals(1, controls.get(0).getSubgroupThreadCount());
Assert.assertEquals(2, controls.get(1).getSubgroupThreadCount());
Assert.assertEquals(2, controls.get(2).getSubgroupThreadCount());
Assert.assertEquals(0, controls.get(3).getSubgroupThreadIndex());
Assert.assertEquals(0, controls.get(4).getSubgroupThreadIndex());
Assert.assertEquals(1, controls.get(5).getSubgroupThreadIndex());
}
}
| 15,068 | 48.084691 | 93 | java |
jmh | jmh-master/jmh-core/src/test/java/org/openjdk/jmh/runner/RunnerTest.java | /*
* Copyright (c) 2014, 2014, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package org.openjdk.jmh.runner;
import org.junit.Test;
import org.openjdk.jmh.annotations.Mode;
import org.openjdk.jmh.infra.BenchmarkParams;
import org.openjdk.jmh.infra.IterationParams;
import org.openjdk.jmh.profile.ExternalProfiler;
import org.openjdk.jmh.runner.options.OptionsBuilder;
import org.openjdk.jmh.runner.options.TimeValue;
import org.openjdk.jmh.util.FileUtils;
import org.openjdk.jmh.util.Utils;
import org.openjdk.jmh.util.Version;
import java.io.File;
import java.io.IOException;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Set;
import java.util.concurrent.TimeUnit;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
public class RunnerTest {
private static final String DUMMY_HOST = "host";
private static final int DUMMY_PORT = 42;
static Set<String> defaultHints = CompilerHints.fromFile(CompilerHints.hintsFile()).get();
@Test(expected = IllegalArgumentException.class)
public void testNullCheck() {
new Runner(null);
}
@Test
public void testEmptyOptsHaveCompileCommandFile() {
Runner blade = new Runner(new OptionsBuilder());
BenchmarkParams bp = new BenchmarkParams("Foo", "bar", false,
1, new int[]{1}, Collections.<String>emptyList(),
1, 1,
new IterationParams(IterationType.WARMUP, 1, TimeValue.seconds(1), 1),
new IterationParams(IterationType.MEASUREMENT, 1, TimeValue.seconds(1), 1),
Mode.Throughput, null, TimeUnit.SECONDS, 1,
Utils.getCurrentJvm(), Collections.<String>emptyList(),
System.getProperty("java.version"), System.getProperty("java.vm.name"), System.getProperty("java.vm.version"), Version.getPlainVersion(),
TimeValue.days(1));
List<String> command = blade.getForkedMainCommand(bp, Collections.<ExternalProfiler>emptyList(), DUMMY_HOST, DUMMY_PORT);
// expecting 1 compile command file
List<String> files = CompilerHints.getCompileCommandFiles(command);
assertEquals(1, files.size());
// file should exist
final String hintFileName = files.get(0);
File hintsFile = new File(hintFileName);
assertTrue(hintsFile.exists());
// hints should be the default as none were specified
Set<String> hints = CompilerHints.fromFile(hintFileName).get();
assertEquals(hints, defaultHints);
}
@Test
public void testOptsWithCompileCommandFileResultInMergedCompileCommandFile() throws IOException {
// add a hints file
String tempHints = FileUtils.createTempFileWithLines("fileWithLines",
Collections.singletonList("inline,we/like/to/move/it.*"));
Set<String> extraHints = CompilerHints.fromFile(tempHints).get();
Runner blade = new Runner(new OptionsBuilder().build());
BenchmarkParams bp = new BenchmarkParams("Foo", "bar", false,
1, new int[]{1}, Collections.<String>emptyList(),
1, 1,
new IterationParams(IterationType.WARMUP, 1, TimeValue.seconds(1), 1),
new IterationParams(IterationType.MEASUREMENT, 1, TimeValue.seconds(1), 1),
Mode.Throughput, null, TimeUnit.SECONDS, 1,
Utils.getCurrentJvm(), Collections.singletonList(CompilerHints.XX_COMPILE_COMMAND_FILE + tempHints),
System.getProperty("java.version"), System.getProperty("java.vm.name"), System.getProperty("java.vm.version"), Version.getPlainVersion(),
TimeValue.days(1));
List<String> command = blade.getForkedMainCommand(bp, Collections.<ExternalProfiler>emptyList(), DUMMY_HOST, DUMMY_PORT);
// expecting 1 compile command file
List<String> files = CompilerHints.getCompileCommandFiles(command);
assertEquals(1, files.size());
// file should exist
final String hintFileName = files.get(0);
File hintsFile = new File(hintFileName);
assertTrue(hintsFile.exists());
// hints should include defaults and specified
Set<String> hints = CompilerHints.fromFile(hintFileName).get();
assertTrue(hints.containsAll(defaultHints));
assertTrue(hints.containsAll(extraHints));
}
@Test
public void testOptsWith2CompileCommandFilesResultInMergedCompileCommandFile() throws IOException {
// add hints files
String tempHints1 = FileUtils.createTempFileWithLines("fileWithLines",
Collections.singletonList("inline,we/like/to/move/it/move/it.*"));
Set<String> extraHints1 = CompilerHints.fromFile(tempHints1).get();
String tempHints2 = FileUtils.createTempFileWithLines("fileWithLines",
Collections.singletonList("inline,we/like/to/move/it.*"));
Set<String> extraHints2 = CompilerHints.fromFile(tempHints2).get();
Runner blade = new Runner(new OptionsBuilder().build());
BenchmarkParams bp = new BenchmarkParams("Foo", "bar", false,
1, new int[]{1}, Collections.<String>emptyList(),
1, 1,
new IterationParams(IterationType.WARMUP, 1, TimeValue.seconds(1), 1),
new IterationParams(IterationType.MEASUREMENT, 1, TimeValue.seconds(1), 1),
Mode.Throughput, null, TimeUnit.SECONDS, 1,
Utils.getCurrentJvm(),
Arrays.asList(CompilerHints.XX_COMPILE_COMMAND_FILE + tempHints1, CompilerHints.XX_COMPILE_COMMAND_FILE + tempHints2),
System.getProperty("java.version"), System.getProperty("java.vm.name"), System.getProperty("java.vm.version"), Version.getPlainVersion(),
TimeValue.days(1));
List<String> command = blade.getForkedMainCommand(bp, Collections.<ExternalProfiler>emptyList(), DUMMY_HOST, DUMMY_PORT);
// expecting 1 compile command file
List<String> files = CompilerHints.getCompileCommandFiles(command);
assertEquals(1, files.size());
// file should exist
final String hintFileName = files.get(0);
File hintsFile = new File(hintFileName);
assertTrue(hintsFile.exists());
// hints should include defaults and specified
Set<String> hints = CompilerHints.fromFile(hintFileName).get();
assertTrue(hints.containsAll(defaultHints));
assertTrue(hints.containsAll(extraHints1));
assertTrue(hints.containsAll(extraHints2));
}
}
| 7,746 | 48.031646 | 153 | java |
jmh | jmh-master/jmh-core/src/test/java/org/openjdk/jmh/runner/TestBenchmarkList.java | /*
* Copyright (c) 2005, 2013, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package org.openjdk.jmh.runner;
import org.junit.BeforeClass;
import org.junit.Test;
import org.openjdk.jmh.annotations.Mode;
import org.openjdk.jmh.runner.format.OutputFormat;
import org.openjdk.jmh.runner.format.OutputFormatFactory;
import org.openjdk.jmh.runner.options.TimeValue;
import org.openjdk.jmh.runner.options.VerboseMode;
import org.openjdk.jmh.util.Optional;
import java.util.*;
import java.util.concurrent.TimeUnit;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
/**
* Tests for BenchmarkList
*/
public class TestBenchmarkList {
private static BenchmarkList list;
private static OutputFormat out;
private static void stub(StringBuilder sb, String userClassQName, String generatedClassQName, String method, Mode mode) {
BenchmarkListEntry br = new BenchmarkListEntry(
userClassQName,
generatedClassQName,
method,
mode,
Optional.<Integer>none(),
new int[]{1},
Optional.<Collection<String>>none(),
Optional.<Integer>none(),
Optional.<TimeValue>none(),
Optional.<Integer>none(),
Optional.<Integer>none(),
Optional.<TimeValue>none(),
Optional.<Integer>none(),
Optional.<Integer>none(),
Optional.<Integer>none(),
Optional.<String>none(),
Optional.<Collection<String>>none(),
Optional.<Collection<String>>none(),
Optional.<Collection<String>>none(),
Optional.<Map<String, String[]>>none(),
Optional.<TimeUnit>none(),
Optional.<Integer>none(),
Optional.<TimeValue>none()
);
sb.append(br.toLine());
sb.append(String.format("%n"));
}
@BeforeClass
public static void setUpClass() {
StringBuilder sb = new StringBuilder();
stub(sb,
"oracle.micro.benchmarks.api.java.util.concurrent.NormalMaps",
"oracle.micro.benchmarks.api.java.util.concurrent.generated.NormalMaps",
"testConcurrentHashMap",
Mode.AverageTime);
stub(sb,
"oracle.micro.benchmarks.app.jbb05.GeneratedSPECjbb2005HashMap",
"oracle.micro.benchmarks.app.jbb05.generated.GeneratedSPECjbb2005HashMap",
"jbb2005HashMapGetIntThroughput",
Mode.AverageTime);
stub(sb,
"oracle.micro.benchmarks.app.jbb05.GeneratedSPECjbb2005HashMap",
"oracle.micro.benchmarks.app.jbb05.generated.GeneratedSPECjbb2005HashMap",
"jbb2005HashMapGetIntGCThroughput",
Mode.AverageTime);
stub(sb,
"oracle.micro.benchmarks.app.jbb05.GeneratedSPECjbb2005HashMap",
"oracle.micro.benchmarks.app.jbb05.generated.GeneratedSPECjbb2005HashMap",
"jbb2005HashMapGetIntegerThroughput",
Mode.AverageTime);
stub(sb,
"oracle.micro.benchmarks.app.jbb05.GeneratedSPECjbb2005HashMap",
"oracle.micro.benchmarks.app.jbb05.generated.GeneratedSPECjbb2005HashMap",
"jbb2005ResizedHashMapGetIntThroughput",
Mode.AverageTime);
stub(sb,
"oracle.micro.benchmarks.app.jbb05.GeneratedSPECjbb2005HashMap",
"oracle.micro.benchmarks.app.jbb05.generated.GeneratedSPECjbb2005HashMap",
"jbb2005ResizedHashMapGetIntegerThroughput",
Mode.AverageTime);
stub(sb,
"oracle.micro.benchmarks.app.sjent.GeneratedPrintBase64",
"oracle.micro.benchmarks.app.sjent.generated.GeneratedPrintBase64",
"printBase64Binary_128bytesThroughput",
Mode.AverageTime);
stub(sb,
"oracle.micro.benchmarks.app.sjent.GeneratedPrintBase64",
"oracle.micro.benchmarks.app.sjent.generated.GeneratedPrintBase64",
"printBase64Binary_32bytesThroughput",
Mode.AverageTime);
stub(sb,
"oracle.micro.benchmarks.app.sjent.GeneratedPrintBase64",
"oracle.micro.benchmarks.app.sjent.generated.GeneratedPrintBase64",
"printBase64Binary_512bytesThroughput",
Mode.AverageTime);
stub(sb,
"oracle.micro.benchmarks.api.java.util.concurrent.GeneratedMaps",
"oracle.micro.benchmarks.api.java.util.concurrent.generated.GeneratedMaps",
"testConcurrentHashMap",
Mode.AverageTime);
stub(sb,
"org.openjdk.jmh.runner.TestMicro",
"org.openjdk.jmh.runner.generated.TestMicro",
"dummy",
Mode.AverageTime);
stub(sb,
"org.openjdk.jmh.runner.TestMicro",
"org.openjdk.jmh.runner.generated.TestMicro",
"dummyWarmThroughput",
Mode.AverageTime);
stub(sb,
"org.openjdk.jmh.runner.TestMicro",
"org.openjdk.jmh.runner.generated.TestMicro",
"dummyWarmOnlyThroughput",
Mode.AverageTime);
stub(sb,
"org.openjdk.jmh.runner.TestMicro",
"org.openjdk.jmh.runner.generated.TestMicro",
"dummySetupPayloadThroughput",
Mode.AverageTime);
stub(sb,
"org.openjdk.jmh.runner.TestMicro",
"org.openjdk.jmh.runner.generated.TestMicro",
"boom_ExceptionThroughput",
Mode.AverageTime);
stub(sb,
"org.openjdk.jmh.runner.TestMicro",
"org.openjdk.jmh.runner.generated.TestMicro",
"boom_ErrorThroughput",
Mode.AverageTime);
stub(sb,
"org.openjdk.jmh.runner.TestMicro",
"org.openjdk.jmh.runner.generated.TestMicro",
"boom_ThrowableThroughput",
Mode.AverageTime);
stub(sb,
"org.openjdk.jmh.runner.TestMicro",
"org.openjdk.jmh.runner.generated.TestMicro",
"blackholedThroughput",
Mode.AverageTime);
stub(sb,
"org.openjdk.jmh.runner.TestBrokenMicro",
"org.openjdk.jmh.runner.generated.TestBrokenMicro",
"dummyPayloadThroughput",
Mode.AverageTime);
stub(sb,
"org.openjdk.jmh.runner.TestExceptionThrowingMicro",
"org.openjdk.jmh.runner.generated.TestExceptionThrowingMicro",
"ouchThroughput",
Mode.AverageTime);
list = BenchmarkList.fromString(sb.toString());
out = OutputFormatFactory.createFormatInstance(System.out, VerboseMode.NORMAL);
}
@Test
public void testListGetNothing() {
// make sure we get nothing
List<String> excludes = Collections.singletonList(".*");
Set<BenchmarkListEntry> micros = list.getAll(out, excludes);
assertEquals(0, micros.size());
}
@Test
public void testListGetAll() {
// make sure we get em all
List<String> excludes = Collections.emptyList();
Set<BenchmarkListEntry> micros = list.getAll(out, excludes);
assertEquals(20, micros.size());
}
@Test
public void testListFindSingleByPattern() {
// check find without excludes
List<String> includes = Collections.singletonList(".*Hash.*");
List<String> excludes = Collections.emptyList();
Set<BenchmarkListEntry> micros = list.find(out, includes, excludes);
assertEquals(7, micros.size());
}
@Test
public void testListFindSingleBySubstring() {
// check find without excludes
List<String> includes = Collections.singletonList("Hash");
List<String> excludes = Collections.emptyList();
Set<BenchmarkListEntry> micros = list.find(out, includes, excludes);
assertEquals(7, micros.size());
}
@Test
public void testListFindSingleByTypical() {
// check find without excludes
// this would be a typical partial pattern with . abuse case
List<String> includes = Collections.singletonList("jbb05.GeneratedSPECjbb2005HashMap");
List<String> excludes = Collections.emptyList();
Set<BenchmarkListEntry> micros = list.find(out, includes, excludes);
assertEquals(5, micros.size());
}
@Test
public void testListFindAnchored() {
// check find without excludes
// matches only: org.openjdk.jmh.runner.TestMicro.dummy
List<String> includes = Collections.singletonList("^org\\.openjdk.*\\.dummy$");
List<String> excludes = Collections.emptyList();
Set<BenchmarkListEntry> micros = list.find(out, includes, excludes);
assertEquals(1, micros.size());
}
@Test
public void testListFindSingleWithExcludes() {
// check find with excludes
List<String> includes = Collections.singletonList(".*Hash.*");
List<String> excludes = Collections.singletonList(".*Int.*");
Set<BenchmarkListEntry> micros = list.find(out, includes, excludes);
assertEquals(2, micros.size());
}
@Test
public void testListFindAllWithSubstringExclude() {
// check find with excludes
List<String> includes = Collections.singletonList("");
List<String> excludes = Collections.singletonList("oracle");
Set<BenchmarkListEntry> micros = list.find(out, includes, excludes);
assertEquals(10, micros.size());
}
@Test
public void testListFindAllWithEmpty() {
List<String> includes = Collections.emptyList();
List<String> excludes = Collections.emptyList();
Set<BenchmarkListEntry> micros = list.find(out, includes, excludes);
assertEquals(20, micros.size());
}
@Test
public void testListFindIncludeList() {
// check find with excludes
List<String> includes = Arrays.asList("^oracle", ".*openjmh.*");
List<String> excludes = Collections.emptyList();
Set<BenchmarkListEntry> micros = list.find(out, includes, excludes);
assertEquals(10, micros.size());
}
@Test
public void testListFindWithIncludesAndExcludes() {
List<String> includes = Collections.singletonList(".*Concurrent.*");
List<String> excludes = Collections.singletonList(".*Int.*");
Set<BenchmarkListEntry> micros = list.find(out, includes, excludes);
assertEquals(2, micros.size());
}
@Test
public void testListIsSorted() {
// micros should be sorted
List<String> includes = Collections.singletonList(".*Hash.*");
List<String> excludes = Collections.singletonList(".*Int.*");
Set<BenchmarkListEntry> micros = list.find(out, includes, excludes);
BenchmarkListEntry first = micros.iterator().next();
assertTrue("oracle.micro.benchmarks.api.java.util.concurrent.GeneratedMaps.testConcurrentHashMap".equals(first.getUsername()));
}
}
| 12,501 | 38.563291 | 135 | java |
jmh | jmh-master/jmh-core/src/test/java/org/openjdk/jmh/runner/TestBenchmarkListEncoding.java | /*
* Copyright (c) 2017, Red Hat Inc. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package org.openjdk.jmh.runner;
import org.junit.Test;
import org.openjdk.jmh.annotations.Mode;
import org.openjdk.jmh.runner.options.TimeValue;
import org.openjdk.jmh.util.Optional;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.lang.reflect.Field;
import java.nio.charset.Charset;
import java.util.*;
import java.util.concurrent.TimeUnit;
import static org.junit.Assert.assertEquals;
public class TestBenchmarkListEncoding {
private static BenchmarkListEntry stub(String userClassQName, String generatedClassQName, String method, Mode mode) {
BenchmarkListEntry br = new BenchmarkListEntry(
userClassQName,
generatedClassQName,
method,
mode,
Optional.<Integer>none(),
new int[]{1},
Optional.<Collection<String>>none(),
Optional.<Integer>none(),
Optional.<TimeValue>none(),
Optional.<Integer>none(),
Optional.<Integer>none(),
Optional.<TimeValue>none(),
Optional.<Integer>none(),
Optional.<Integer>none(),
Optional.<Integer>none(),
Optional.<String>none(),
Optional.<Collection<String>>none(),
Optional.<Collection<String>>none(),
Optional.<Collection<String>>none(),
Optional.<Map<String, String[]>>none(),
Optional.<TimeUnit>none(),
Optional.<Integer>none(),
Optional.<TimeValue>none()
);
return br;
}
@Test
public void test_ASCII_UTF8() throws Exception {
testWith("ASCII", "UTF-8");
}
@Test
public void test_UTF8_ASCII() throws Exception {
testWith("UTF-8", "ASCII");
}
@Test
public void test_UTF8_UTF8() throws Exception {
testWith("UTF-8", "UTF-8");
}
@Test
public void test_ASCII_ASCII() throws Exception {
testWith("ASCII", "ASCII");
}
public void testWith(String src, String dst) throws IOException {
BenchmarkListEntry br = stub("something.Test",
"something.generated.Test",
"testКонкаррентХэшмап",
Mode.AverageTime);
resetCharset();
System.setProperty("file.encoding", src);
ByteArrayOutputStream bos = new ByteArrayOutputStream();
BenchmarkList.writeBenchmarkList(bos, Collections.singleton(br));
resetCharset();
System.setProperty("file.encoding", dst);
ByteArrayInputStream bis = new ByteArrayInputStream(bos.toByteArray());
List<BenchmarkListEntry> read = BenchmarkList.readBenchmarkList(bis);
assertEquals("something.Test.testКонкаррентХэшмап", read.get(0).getUsername());
}
private void resetCharset() {
try {
Field f = Charset.class.getDeclaredField("defaultCharset");
f.setAccessible(true);
f.set(null, null);
} catch (Exception e) {
// okay then.
}
}
}
| 4,341 | 34.884298 | 121 | java |
jmh | jmh-master/jmh-core/src/test/java/org/openjdk/jmh/runner/TestBenchmarkListSorting.java | /*
* Copyright (c) 2021, Red Hat Inc. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package org.openjdk.jmh.runner;
import org.junit.Test;
import org.openjdk.jmh.annotations.Mode;
import org.openjdk.jmh.runner.options.TimeValue;
import org.openjdk.jmh.util.Optional;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.util.*;
import java.util.concurrent.TimeUnit;
import static org.junit.Assert.assertEquals;
public class TestBenchmarkListSorting {
private static BenchmarkListEntry stub(String userClassQName, String generatedClassQName, String method, Mode mode) {
BenchmarkListEntry br = new BenchmarkListEntry(
userClassQName,
generatedClassQName,
method,
mode,
Optional.<Integer>none(),
new int[]{1},
Optional.<Collection<String>>none(),
Optional.<Integer>none(),
Optional.<TimeValue>none(),
Optional.<Integer>none(),
Optional.<Integer>none(),
Optional.<TimeValue>none(),
Optional.<Integer>none(),
Optional.<Integer>none(),
Optional.<Integer>none(),
Optional.<String>none(),
Optional.<Collection<String>>none(),
Optional.<Collection<String>>none(),
Optional.<Collection<String>>none(),
Optional.<Map<String, String[]>>none(),
Optional.<TimeUnit>none(),
Optional.<Integer>none(),
Optional.<TimeValue>none()
);
return br;
}
@Test
public void test() throws Exception {
BenchmarkListEntry br1 = stub("something.Test1",
"something.generated.Test1",
"something.generated.TestMethod",
Mode.AverageTime);
BenchmarkListEntry br2 = stub("something.Test2",
"something.generated.Test1",
"something.generated.TestMethod",
Mode.AverageTime);
BenchmarkListEntry br3 = stub("something.Test3",
"something.generated.Test1",
"something.generated.TestMethod",
Mode.AverageTime);
BenchmarkListEntry br4 = stub("something.Test4",
"something.generated.Test1",
"something.generated.TestMethod",
Mode.AverageTime);
// Present to writer in mixed order
ByteArrayOutputStream bos = new ByteArrayOutputStream();
BenchmarkList.writeBenchmarkList(bos, Arrays.asList(br4, br2, br3, br1));
ByteArrayInputStream bis = new ByteArrayInputStream(bos.toByteArray());
List<BenchmarkListEntry> read = BenchmarkList.readBenchmarkList(bis);
// Assert we read these in proper order
assertEquals("something.Test1", read.get(0).getUserClassQName());
assertEquals("something.Test2", read.get(1).getUserClassQName());
assertEquals("something.Test3", read.get(2).getUserClassQName());
assertEquals("something.Test4", read.get(3).getUserClassQName());
}
}
| 4,280 | 40.163462 | 121 | java |
jmh | jmh-master/jmh-core/src/test/java/org/openjdk/jmh/runner/options/TestIncludes.java | /*
* Copyright (c) 2005, 2014, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package org.openjdk.jmh.runner.options;
import org.junit.Assert;
import org.junit.Test;
public class TestIncludes {
@Test
public void testCmdLine_OptBuilder() throws CommandLineOptionException {
Options opts = new OptionsBuilder()
.parent(new CommandLineOptions())
.include(".*boo.*")
.build();
Assert.assertEquals(1, opts.getIncludes().size());
Assert.assertEquals(".*boo.*", opts.getIncludes().get(0));
}
@Test
public void testOptBuilder_OptBuilder() {
Options opts = new OptionsBuilder()
.parent(new OptionsBuilder().build())
.include(".*boo.*")
.build();
Assert.assertEquals(1, opts.getIncludes().size());
Assert.assertEquals(".*boo.*", opts.getIncludes().get(0));
}
}
| 2,059 | 37.867925 | 79 | java |
jmh | jmh-master/jmh-core/src/test/java/org/openjdk/jmh/runner/options/TestOptions.java | /*
* Copyright (c) 2005, 2013, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package org.openjdk.jmh.runner.options;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.openjdk.jmh.annotations.Mode;
import org.openjdk.jmh.annotations.Threads;
import org.openjdk.jmh.results.format.ResultFormatType;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;
import java.util.Collection;
import java.util.concurrent.TimeUnit;
public class TestOptions {
private Options EMPTY_BUILDER;
private CommandLineOptions EMPTY_CMDLINE;
@Before
public void setUp() throws Exception {
EMPTY_CMDLINE = new CommandLineOptions();
EMPTY_BUILDER = new OptionsBuilder().build();
}
@Test
public void testSerializable_Cmdline() throws IOException {
ObjectOutputStream oos = new ObjectOutputStream(new ByteArrayOutputStream());
oos.writeObject(EMPTY_CMDLINE);
oos.flush();
}
@Test
public void testSerializable_Builder() throws IOException {
ObjectOutputStream oos = new ObjectOutputStream(new ByteArrayOutputStream());
oos.writeObject(EMPTY_BUILDER);
oos.flush();
}
@Test
public void testIncludes() throws Exception {
CommandLineOptions cmdLine = new CommandLineOptions(".*", ".*test.*", "test");
Options builder = new OptionsBuilder().include(".*").include(".*test.*").include("test").build();
Assert.assertEquals(builder.getIncludes(), cmdLine.getIncludes());
}
@Test
public void testIncludes_Default() {
Assert.assertEquals(EMPTY_BUILDER.getIncludes(), EMPTY_CMDLINE.getIncludes());
}
@Test
public void testExcludes() throws Exception {
CommandLineOptions cmdLine = new CommandLineOptions("-e", ".*", "-e", ".*test.*", "-e", "test");
Options builder = new OptionsBuilder().exclude(".*").exclude(".*test.*").exclude("test").build();
Assert.assertEquals(builder.getExcludes(), cmdLine.getExcludes());
}
@Test
public void testExcludes_Default() {
Assert.assertEquals(EMPTY_BUILDER.getExcludes(), EMPTY_CMDLINE.getExcludes());
}
@Test
public void testOutput() throws Exception {
CommandLineOptions cmdLine = new CommandLineOptions("-o", "sample.out");
Options builder = new OptionsBuilder().output("sample.out").build();
Assert.assertEquals(builder.getOutput(), cmdLine.getOutput());
}
@Test
public void testOutput_Default() {
Assert.assertEquals(EMPTY_BUILDER.getOutput(), EMPTY_CMDLINE.getOutput());
}
@Test
public void testResultFormats() throws Exception {
for (ResultFormatType type : ResultFormatType.values()) {
CommandLineOptions cmdLine = new CommandLineOptions("-rf", type.toString());
Options builder = new OptionsBuilder().resultFormat(type).build();
Assert.assertEquals(builder.getResultFormat(), cmdLine.getResultFormat());
}
}
@Test
public void testResultFormats_UC() throws Exception {
for (ResultFormatType type : ResultFormatType.values()) {
CommandLineOptions cmdLine = new CommandLineOptions("-rf", type.toString().toUpperCase());
Options builder = new OptionsBuilder().resultFormat(type).build();
Assert.assertEquals(builder.getResultFormat(), cmdLine.getResultFormat());
}
}
@Test
public void testResultFormats_LC() throws Exception {
for (ResultFormatType type : ResultFormatType.values()) {
CommandLineOptions cmdLine = new CommandLineOptions("-rf", type.toString().toLowerCase());
Options builder = new OptionsBuilder().resultFormat(type).build();
Assert.assertEquals(builder.getResultFormat(), cmdLine.getResultFormat());
}
}
@Test
public void testResultFormats_Default() {
Assert.assertEquals(EMPTY_BUILDER.getResultFormat(), EMPTY_CMDLINE.getResultFormat());
}
@Test
public void testResult() throws Exception {
CommandLineOptions cmdLine = new CommandLineOptions("-rff", "sample.out");
Options builder = new OptionsBuilder().result("sample.out").build();
Assert.assertEquals(builder.getOutput(), cmdLine.getOutput());
}
@Test
public void testResult_Default() {
Assert.assertEquals(EMPTY_BUILDER.getResult(), EMPTY_CMDLINE.getResult());
}
@Test
public void testGC_True() throws Exception {
CommandLineOptions cmdLine = new CommandLineOptions("-gc", "true");
Options builder = new OptionsBuilder().shouldDoGC(true).build();
Assert.assertEquals(builder.getOutput(), cmdLine.getOutput());
}
@Test
public void testGC_False() throws Exception {
CommandLineOptions cmdLine = new CommandLineOptions("-gc", "false");
Options builder = new OptionsBuilder().shouldDoGC(false).build();
Assert.assertEquals(builder.getOutput(), cmdLine.getOutput());
}
@Test
public void testGC_Default() {
Assert.assertEquals(EMPTY_BUILDER.shouldDoGC(), EMPTY_CMDLINE.shouldDoGC());
}
@Test
public void testProfilers() throws Exception {
CommandLineOptions cmdLine = new CommandLineOptions("-prof", "cl", "-prof", "comp");
Options builder = new OptionsBuilder().addProfiler("cl").addProfiler("comp").build();
Assert.assertEquals(builder.getProfilers(), cmdLine.getProfilers());
}
@Test
public void testProfilers_Default() {
Assert.assertEquals(EMPTY_BUILDER.getProfilers(), EMPTY_CMDLINE.getProfilers());
}
@Test
public void testVerbose() throws Exception {
for (VerboseMode mode : VerboseMode.values()) {
CommandLineOptions cmdLine = new CommandLineOptions("-v", mode.toString());
Options builder = new OptionsBuilder().verbosity(mode).build();
Assert.assertEquals(builder.verbosity(), cmdLine.verbosity());
}
}
@Test
public void testVerbose_LC() throws Exception {
for (VerboseMode mode : VerboseMode.values()) {
CommandLineOptions cmdLine = new CommandLineOptions("-v", mode.toString().toLowerCase());
Options builder = new OptionsBuilder().verbosity(mode).build();
Assert.assertEquals(builder.verbosity(), cmdLine.verbosity());
}
}
@Test
public void testVerbose_UC() throws Exception {
for (VerboseMode mode : VerboseMode.values()) {
CommandLineOptions cmdLine = new CommandLineOptions("-v", mode.toString().toUpperCase());
Options builder = new OptionsBuilder().verbosity(mode).build();
Assert.assertEquals(builder.verbosity(), cmdLine.verbosity());
}
}
@Test
public void testVerbose_Default() {
Assert.assertEquals(EMPTY_BUILDER.verbosity(), EMPTY_CMDLINE.verbosity());
}
@Test
public void testSFOE_True() throws Exception {
CommandLineOptions cmdLine = new CommandLineOptions("-foe", "true");
Options builder = new OptionsBuilder().shouldFailOnError(true).build();
Assert.assertEquals(builder.shouldFailOnError(), cmdLine.shouldFailOnError());
}
@Test
public void testSFOE_False() throws Exception {
CommandLineOptions cmdLine = new CommandLineOptions("-foe", "false");
Options builder = new OptionsBuilder().shouldFailOnError(false).build();
Assert.assertEquals(builder.shouldFailOnError(), cmdLine.shouldFailOnError());
}
@Test
public void testSFOE_Default() {
Assert.assertEquals(EMPTY_BUILDER.shouldFailOnError(), EMPTY_CMDLINE.shouldFailOnError());
}
@Test
public void testThreads_Set() throws Exception {
CommandLineOptions cmdLine = new CommandLineOptions("-t", "2");
Options builder = new OptionsBuilder().threads(2).build();
Assert.assertEquals(builder.getThreads(), cmdLine.getThreads());
}
@Test
public void testThreads_Max() throws Exception {
CommandLineOptions cmdLine = new CommandLineOptions("-t", "max");
Options builder = new OptionsBuilder().threads(Threads.MAX).build();
Assert.assertEquals(builder.getThreads(), cmdLine.getThreads());
}
@Test
public void testThreads_Zero() {
try {
new CommandLineOptions("-t", "0");
Assert.fail();
} catch (CommandLineOptionException e) {
Assert.assertEquals("Cannot parse argument '0' of option t. The given value 0 should be positive", e.getMessage());
}
}
@Test
public void testThreads_Zero_OptionsBuilder() {
try {
new OptionsBuilder().threads(0);
Assert.fail();
} catch (IllegalArgumentException e) {
Assert.assertEquals("Threads (0) should be positive", e.getMessage());
}
}
@Test
public void testThreads_MinusOne() {
try {
new CommandLineOptions("-t", "-1");
Assert.fail();
} catch (CommandLineOptionException e) {
Assert.assertEquals("Cannot parse argument '-1' of option t. The given value -1 should be positive", e.getMessage());
}
}
@Test
public void testThreads_Minus42() {
try {
new CommandLineOptions("-t", "-42");
Assert.fail();
} catch (CommandLineOptionException e) {
Assert.assertEquals("Cannot parse argument '-42' of option t. The given value -42 should be positive", e.getMessage());
}
}
@Test
public void testThreads_Minus42_OptionsBuilder() {
try {
new OptionsBuilder().threads(-42);
} catch (IllegalArgumentException e) {
Assert.assertEquals("Threads (-42) should be positive", e.getMessage());
}
}
@Test
public void testThreads_Default() {
Assert.assertEquals(EMPTY_BUILDER.getThreads(), EMPTY_CMDLINE.getThreads());
}
@Test
public void testThreadGroups() throws Exception {
CommandLineOptions cmdLine = new CommandLineOptions("-tg", "3,4");
Options builder = new OptionsBuilder().threadGroups(3, 4).build();
Assert.assertEquals(builder.getThreads(), cmdLine.getThreads());
}
@Test
public void testThreadGroups_Default() {
Assert.assertEquals(EMPTY_BUILDER.getThreadGroups(), EMPTY_CMDLINE.getThreadGroups());
}
@Test
public void testThreadGroups_WithZero() throws Exception {
CommandLineOptions cmdLine = new CommandLineOptions("-tg", "3,4,0");
Options builder = new OptionsBuilder().threadGroups(3, 4, 0).build();
Assert.assertEquals(builder.getThreads(), cmdLine.getThreads());
}
@Test
public void testThreadGroups_AllZero() {
try {
new CommandLineOptions("-tg", "0,0,0");
Assert.fail();
} catch (CommandLineOptionException e) {
Assert.assertEquals("Group thread count should be positive, but it is 0", e.getMessage());
}
}
@Test
public void testThreadGroups_AllZero_OptionsBuilder() {
try {
new OptionsBuilder().threadGroups(0, 0, 0);
Assert.fail();
} catch (IllegalArgumentException e) {
Assert.assertEquals("Group thread count (0) should be positive", e.getMessage());
}
}
@Test
public void testThreadGroups_WithNegative() {
try {
new CommandLineOptions("-tg", "-1,-2");
Assert.fail();
} catch (CommandLineOptionException e) {
Assert.assertEquals("Cannot parse argument '-1' of option tg. The given value -1 should be non-negative", e.getMessage());
}
}
@Test
public void testThreadGroups_WithNegative_OptionsBuilder() {
try {
new OptionsBuilder().threadGroups(-1,-2);
Assert.fail();
} catch (IllegalArgumentException e) {
Assert.assertEquals("Group #0 thread count (-1) should be non-negative", e.getMessage());
}
}
@Test
public void testSynchIterations_True() throws Exception {
CommandLineOptions cmdLine = new CommandLineOptions("-si", "true");
Options builder = new OptionsBuilder().syncIterations(true).build();
Assert.assertEquals(builder.shouldSyncIterations(), cmdLine.shouldSyncIterations());
}
@Test
public void testSynchIterations_False() throws Exception {
CommandLineOptions cmdLine = new CommandLineOptions("-si", "false");
Options builder = new OptionsBuilder().syncIterations(false).build();
Assert.assertEquals(builder.shouldSyncIterations(), cmdLine.shouldSyncIterations());
}
@Test
public void testSynchIterations_Default() {
Assert.assertEquals(EMPTY_BUILDER.shouldSyncIterations(), EMPTY_CMDLINE.shouldSyncIterations());
}
@Test
public void testWarmupIterations() throws Exception {
CommandLineOptions cmdLine = new CommandLineOptions("-wi", "34");
Options builder = new OptionsBuilder().warmupIterations(34).build();
Assert.assertEquals(builder.getWarmupIterations(), cmdLine.getWarmupIterations());
}
@Test
public void testWarmupIterations_Default() {
Assert.assertEquals(EMPTY_BUILDER.getWarmupIterations(), EMPTY_CMDLINE.getWarmupIterations());
}
@Test
public void testWarmupIterations_Zero() throws Exception {
CommandLineOptions cmdLine = new CommandLineOptions("-wi", "0");
Options builder = new OptionsBuilder().warmupIterations(0).build();
Assert.assertEquals(builder.getWarmupIterations(), cmdLine.getWarmupIterations());
}
@Test
public void testWarmupIterations_MinusOne() {
try {
new CommandLineOptions("-wi", "-1");
Assert.fail();
} catch (CommandLineOptionException e) {
Assert.assertEquals("Cannot parse argument '-1' of option wi. The given value -1 should be non-negative", e.getMessage());
}
}
@Test
public void testWarmupIterations_MinusOne_OptionsBuilder() {
try {
new OptionsBuilder().warmupIterations(-1);
Assert.fail();
} catch (IllegalArgumentException e) {
Assert.assertEquals("Warmup iterations (-1) should be non-negative", e.getMessage());
}
}
@Test
public void testWarmupTime() throws Exception {
CommandLineOptions cmdLine = new CommandLineOptions("-w", "34ms");
Options builder = new OptionsBuilder().warmupTime(TimeValue.milliseconds(34)).build();
Assert.assertEquals(builder.getWarmupTime(), cmdLine.getWarmupTime());
}
@Test
public void testWarmupTime_Default() {
Assert.assertEquals(EMPTY_BUILDER.getWarmupTime(), EMPTY_CMDLINE.getWarmupTime());
}
@Test
public void testRuntimeIterations() throws Exception {
CommandLineOptions cmdLine = new CommandLineOptions("-i", "34");
Options builder = new OptionsBuilder().measurementIterations(34).build();
Assert.assertEquals(builder.getMeasurementIterations(), cmdLine.getMeasurementIterations());
}
@Test
public void testRuntimeIterations_Default() {
Assert.assertEquals(EMPTY_BUILDER.getMeasurementIterations(), EMPTY_CMDLINE.getMeasurementIterations());
}
@Test
public void testRuntimeIterations_Zero() {
try {
new CommandLineOptions("-i", "0");
Assert.fail();
} catch (CommandLineOptionException e) {
Assert.assertEquals("Cannot parse argument '0' of option i. The given value 0 should be positive", e.getMessage());
}
}
@Test
public void testRuntimeIterations_Zero_OptionsBuilder() {
try {
new OptionsBuilder().measurementIterations(0);
Assert.fail();
} catch (IllegalArgumentException e) {
Assert.assertEquals("Measurement iterations (0) should be positive", e.getMessage());
}
}
@Test
public void testRuntime() throws Exception {
CommandLineOptions cmdLine = new CommandLineOptions("-r", "34ms");
Options builder = new OptionsBuilder().measurementTime(TimeValue.milliseconds(34)).build();
Assert.assertEquals(builder.getMeasurementTime(), cmdLine.getMeasurementTime());
}
@Test
public void testRuntime_Default() {
Assert.assertEquals(EMPTY_BUILDER.getMeasurementTime(), EMPTY_CMDLINE.getMeasurementTime());
}
@Test
public void testWarmupMicros() throws Exception {
CommandLineOptions cmdLine = new CommandLineOptions("-wmb", ".*", "-wmb", ".*test.*", "-wmb", "test");
Options builder = new OptionsBuilder().includeWarmup(".*").includeWarmup(".*test.*").includeWarmup("test").build();
Assert.assertEquals(builder.getWarmupIncludes(), cmdLine.getWarmupIncludes());
}
@Test
public void testWarmupMicros_Default() {
Assert.assertEquals(EMPTY_BUILDER.getWarmupIncludes(), EMPTY_CMDLINE.getWarmupIncludes());
}
@Test
public void testBenchModes() throws Exception {
// TODO: Accept multiple options instead of concatenation?
CommandLineOptions cmdLine = new CommandLineOptions("-bm", Mode.AverageTime.shortLabel() + "," + Mode.Throughput.shortLabel());
Options builder = new OptionsBuilder().mode(Mode.AverageTime).mode(Mode.Throughput).build();
Assert.assertEquals(builder.getBenchModes(), cmdLine.getBenchModes());
}
@Test
public void testBenchModes_Default() {
Assert.assertEquals(EMPTY_BUILDER.getBenchModes(), EMPTY_CMDLINE.getBenchModes());
}
@Test
public void testTimeunit() throws Exception {
CommandLineOptions cmdLine = new CommandLineOptions("-tu", "ns");
Options builder = new OptionsBuilder().timeUnit(TimeUnit.NANOSECONDS).build();
Assert.assertEquals(builder.getTimeUnit(), cmdLine.getTimeUnit());
}
@Test
public void testTimeunit_Default() {
Assert.assertEquals(EMPTY_BUILDER.getTimeUnit(), EMPTY_CMDLINE.getTimeUnit());
}
@Test
public void testOPI() throws Exception {
CommandLineOptions cmdLine = new CommandLineOptions("-opi", "42");
Options builder = new OptionsBuilder().operationsPerInvocation(42).build();
Assert.assertEquals(builder.getTimeUnit(), cmdLine.getTimeUnit());
}
@Test
public void testOPI_Zero() {
try {
new CommandLineOptions("-opi", "0");
Assert.fail();
} catch (CommandLineOptionException e) {
Assert.assertEquals("Cannot parse argument '0' of option opi. The given value 0 should be positive", e.getMessage());
}
}
@Test
public void testOPI_Zero_OptionsBuilder() {
try {
new OptionsBuilder().operationsPerInvocation(0);
Assert.fail();
} catch (IllegalArgumentException e) {
Assert.assertEquals("Operations per invocation (0) should be positive", e.getMessage());
}
}
@Test
public void testOPI_Default() {
Assert.assertEquals(EMPTY_BUILDER.getOperationsPerInvocation(), EMPTY_CMDLINE.getOperationsPerInvocation());
}
@Test
public void testFork_0() throws Exception {
CommandLineOptions cmdLine = new CommandLineOptions("-f", "0");
Options builder = new OptionsBuilder().forks(0).build();
Assert.assertEquals(builder.getForkCount(), cmdLine.getForkCount());
}
@Test
public void testFork_1() throws Exception {
CommandLineOptions cmdLine = new CommandLineOptions("-f", "1");
Options builder = new OptionsBuilder().forks(1).build();
Assert.assertEquals(builder.getForkCount(), cmdLine.getForkCount());
}
@Test
public void testFork_Default() {
Assert.assertEquals(EMPTY_BUILDER.getForkCount(), EMPTY_CMDLINE.getForkCount());
}
@Test
public void testFork_MinusOne() {
try {
new CommandLineOptions("-f", "-1");
Assert.fail();
} catch (CommandLineOptionException e) {
Assert.assertEquals("Cannot parse argument '-1' of option f. The given value -1 should be non-negative", e.getMessage());
}
}
@Test
public void testFork__MinusOne_OptionsBuilder() {
try {
new OptionsBuilder().forks(-1);
Assert.fail();
} catch (IllegalArgumentException e) {
Assert.assertEquals("Forks (-1) should be non-negative", e.getMessage());
}
}
@Test
public void testWarmupFork_0() throws Exception {
CommandLineOptions cmdLine = new CommandLineOptions("-wf", "0");
Options builder = new OptionsBuilder().warmupForks(0).build();
Assert.assertEquals(builder.getWarmupForkCount(), cmdLine.getWarmupForkCount());
}
@Test
public void testWarmupFork_1() throws Exception {
CommandLineOptions cmdLine = new CommandLineOptions("-wf", "1");
Options builder = new OptionsBuilder().warmupForks(1).build();
Assert.assertEquals(builder.getWarmupForkCount(), cmdLine.getWarmupForkCount());
}
@Test
public void testWarmupFork_Default() {
Assert.assertEquals(EMPTY_BUILDER.getWarmupForkCount(), EMPTY_CMDLINE.getWarmupForkCount());
}
@Test
public void testWarmupFork_MinusOne() {
try {
new CommandLineOptions("-wf", "-1");
Assert.fail();
} catch (CommandLineOptionException e) {
Assert.assertEquals("Cannot parse argument '-1' of option wf. The given value -1 should be non-negative", e.getMessage());
}
}
@Test
public void testWarmupFork_MinusOne_OptionsBuilder() {
try {
new OptionsBuilder().warmupForks(-1);
Assert.fail();
} catch (IllegalArgumentException e) {
Assert.assertEquals("Warmup forks (-1) should be non-negative", e.getMessage());
}
}
@Test
public void testJvm() throws Exception {
CommandLineOptions cmdLine = new CommandLineOptions("--jvm", "sample.jar");
Options builder = new OptionsBuilder().jvm("sample.jar").build();
Assert.assertEquals(builder.getJvm(), cmdLine.getJvm());
}
@Test
public void testJvm_Default() {
Assert.assertEquals(EMPTY_BUILDER.getJvm(), EMPTY_CMDLINE.getJvm());
}
@Test
public void testJvmArgs() throws Exception {
CommandLineOptions cmdLine = new CommandLineOptions("--jvmArgs", "sample.jar");
Options builder = new OptionsBuilder().jvmArgs("sample.jar").build();
Assert.assertEquals(builder.getJvmArgs(), cmdLine.getJvmArgs());
}
@Test
public void testJvmArgs_Default() {
Assert.assertEquals(EMPTY_BUILDER.getJvmArgs(), EMPTY_CMDLINE.getJvmArgs());
}
@Test
public void testJvmArgsAppend() throws Exception {
CommandLineOptions cmdLine = new CommandLineOptions("--jvmArgsAppend", "sample.jar");
Options builder = new OptionsBuilder().jvmArgsAppend("sample.jar").build();
Assert.assertEquals(builder.getJvmArgsAppend(), cmdLine.getJvmArgsAppend());
}
@Test
public void testJvmArgsAppend_Default() {
Assert.assertEquals(EMPTY_BUILDER.getJvmArgsAppend(), EMPTY_CMDLINE.getJvmArgsAppend());
}
@Test
public void testJvmArgsPrepend() throws Exception {
CommandLineOptions cmdLine = new CommandLineOptions("--jvmArgsPrepend", "sample.jar");
Options builder = new OptionsBuilder().jvmArgsPrepend("sample.jar").build();
Assert.assertEquals(builder.getJvmArgsPrepend(), cmdLine.getJvmArgsPrepend());
}
@Test
public void testJvmArgsPrepend_Default() {
Assert.assertEquals(EMPTY_BUILDER.getJvmArgsPrepend(), EMPTY_CMDLINE.getJvmArgsPrepend());
}
@Test
public void testBatchSize() throws Exception {
CommandLineOptions cmdLine = new CommandLineOptions("-bs", "42");
Options builder = new OptionsBuilder().measurementBatchSize(42).build();
Assert.assertEquals(builder.getMeasurementBatchSize(), cmdLine.getMeasurementBatchSize());
}
@Test
public void testBatchSize_Default() {
Assert.assertEquals(EMPTY_BUILDER.getMeasurementBatchSize(), EMPTY_CMDLINE.getMeasurementBatchSize());
}
@Test
public void testBatchSize_Zero() {
try {
new CommandLineOptions("-bs", "0");
Assert.fail();
} catch (CommandLineOptionException e) {
Assert.assertEquals("Cannot parse argument '0' of option bs. The given value 0 should be positive", e.getMessage());
}
}
@Test
public void testBatchSize_Zero_OptionsBuilder() {
try {
new OptionsBuilder().measurementBatchSize(0);
Assert.fail();
} catch (IllegalArgumentException e) {
Assert.assertEquals("Measurement batch size (0) should be positive", e.getMessage());
}
}
@Test
public void testWarmupBatchSize() throws Exception {
CommandLineOptions cmdLine = new CommandLineOptions("-wbs", "43");
Options builder = new OptionsBuilder().warmupBatchSize(43).build();
Assert.assertEquals(builder.getWarmupBatchSize(), cmdLine.getWarmupBatchSize());
}
@Test
public void testWarmupBatchSize_Default() {
Assert.assertEquals(EMPTY_BUILDER.getWarmupBatchSize(), EMPTY_CMDLINE.getWarmupBatchSize());
}
@Test
public void testWarmupBatchSize_Zero() {
try {
new CommandLineOptions("-wbs", "0");
Assert.fail();
} catch (CommandLineOptionException e) {
Assert.assertEquals("Cannot parse argument '0' of option wbs. The given value 0 should be positive", e.getMessage());
}
}
@Test
public void testWarmupBatchSize_Zero_OptionsBuilder() {
try {
new OptionsBuilder().warmupBatchSize(0);
Assert.fail();
} catch (IllegalArgumentException e) {
Assert.assertEquals("Warmup batch size (0) should be positive", e.getMessage());
}
}
@Test
public void testParam_Default() {
Assert.assertEquals(EMPTY_BUILDER.getParameter("sample"), EMPTY_CMDLINE.getParameter("sample"));
}
@Test
public void testParam() throws Exception {
CommandLineOptions cmdLine = new CommandLineOptions("-p", "x=1,2,3");
Options builder = new OptionsBuilder().param("x", "1", "2", "3").build();
Collection<String> bp = builder.getParameter("x").get();
Collection<String> cp = cmdLine.getParameter("x").get();
for (String b : bp) {
Assert.assertTrue("CP does not contain: " + b, cp.contains(b));
}
for (String c : cp) {
Assert.assertTrue("BP does not contain: " + c, bp.contains(c));
}
}
@Test
public void testParam_EmptyString() throws Exception {
CommandLineOptions cmdLine = new CommandLineOptions("-p", "x=");
Options builder = new OptionsBuilder().param("x", "").build();
Collection<String> bp = builder.getParameter("x").get();
Collection<String> cp = cmdLine.getParameter("x").get();
for (String b : bp) {
Assert.assertTrue("CP does not contain: " + b, cp.contains(b));
}
for (String c : cp) {
Assert.assertTrue("BP does not contain: " + c, bp.contains(c));
}
}
@Test
public void testTimeout() throws Exception {
CommandLineOptions cmdLine = new CommandLineOptions("-to", "34ms");
Options builder = new OptionsBuilder().timeout(TimeValue.milliseconds(34)).build();
Assert.assertEquals(builder.getTimeout(), cmdLine.getTimeout());
}
@Test
public void testTimeout_Default() {
Assert.assertEquals(EMPTY_BUILDER.getTimeout(), EMPTY_CMDLINE.getTimeout());
}
}
| 29,141 | 36.505792 | 135 | java |
jmh | jmh-master/jmh-core/src/test/java/org/openjdk/jmh/runner/options/TestParentOptions.java | /*
* Copyright (c) 2005, 2014, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package org.openjdk.jmh.runner.options;
import org.junit.Assert;
import org.junit.Test;
import org.openjdk.jmh.annotations.Mode;
import org.openjdk.jmh.results.format.ResultFormatType;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.EnumSet;
import java.util.concurrent.TimeUnit;
public class TestParentOptions {
@Test
public void testIncludes_Empty() {
Options parent = new OptionsBuilder().build();
Options builder = new OptionsBuilder().parent(parent).build();
Assert.assertTrue(builder.getIncludes().isEmpty());
}
@Test
public void testIncludes_Parent() {
Options parent = new OptionsBuilder().include(".*").build();
Options builder = new OptionsBuilder().parent(parent).build();
Assert.assertEquals(Collections.singletonList(".*"), builder.getIncludes());
}
@Test
public void testIncludes_Merge() {
Options parent = new OptionsBuilder().include(".*").build();
Options builder = new OptionsBuilder().parent(parent).include(".*test.*").build();
Assert.assertEquals(Arrays.asList(".*test.*", ".*"), builder.getIncludes());
}
@Test
public void testExcludes_Empty() {
Options parent = new OptionsBuilder().build();
Options builder = new OptionsBuilder().parent(parent).build();
Assert.assertTrue(builder.getExcludes().isEmpty());
}
@Test
public void testExcludes_Parent() {
Options parent = new OptionsBuilder().include(".*").build();
Options builder = new OptionsBuilder().parent(parent).build();
Assert.assertEquals(Collections.singletonList(".*"), builder.getIncludes());
}
@Test
public void testExcludes_Merge() {
Options parent = new OptionsBuilder().exclude(".*").build();
Options builder = new OptionsBuilder().parent(parent).exclude(".*test.*").build();
Assert.assertEquals(Arrays.asList(".*test.*", ".*"), builder.getExcludes());
}
@Test
public void testProfiler_Empty() {
Options parent = new OptionsBuilder().build();
Options builder = new OptionsBuilder().parent(parent).build();
Assert.assertTrue(builder.getProfilers().isEmpty());
}
@Test
public void testProfiler_Parent() {
Options parent = new OptionsBuilder().addProfiler("cl").build();
Options builder = new OptionsBuilder().parent(parent).build();
Assert.assertTrue(builder.getProfilers().size() == 1);
Assert.assertTrue(builder.getProfilers().contains(new ProfilerConfig("cl", "")));
}
@Test
public void testProfiler_Merge() {
Options parent = new OptionsBuilder().addProfiler("cl").build();
Options builder = new OptionsBuilder().parent(parent).addProfiler("comp").build();
Assert.assertTrue(builder.getProfilers().size() == 2);
Assert.assertTrue(builder.getProfilers().contains(new ProfilerConfig("cl", "")));
Assert.assertTrue(builder.getProfilers().contains(new ProfilerConfig("comp", "")));
}
@Test
public void testBenchModes_Empty() {
Options parent = new OptionsBuilder().build();
Options builder = new OptionsBuilder().parent(parent).build();
Assert.assertTrue(builder.getBenchModes().isEmpty());
}
@Test
public void testBenchModes_Parent() {
Options parent = new OptionsBuilder().mode(Mode.AverageTime).build();
Options builder = new OptionsBuilder().parent(parent).build();
Assert.assertEquals(EnumSet.of(Mode.AverageTime), builder.getBenchModes());
}
@Test
public void testBenchModes_Merge() {
Options parent = new OptionsBuilder().mode(Mode.AverageTime).build();
Options builder = new OptionsBuilder().parent(parent).mode(Mode.SingleShotTime).build();
Assert.assertEquals(EnumSet.of(Mode.SingleShotTime), builder.getBenchModes());
}
@Test
public void testForks_Empty() {
Options parent = new OptionsBuilder().build();
Options builder = new OptionsBuilder().parent(parent).build();
Assert.assertFalse(builder.getForkCount().hasValue());
}
@Test
public void testForks_Parent() {
Options parent = new OptionsBuilder().forks(42).build();
Options builder = new OptionsBuilder().parent(parent).build();
Assert.assertEquals(Integer.valueOf(42), builder.getForkCount().get());
}
@Test
public void testForks_Merge() {
Options parent = new OptionsBuilder().forks(42).build();
Options builder = new OptionsBuilder().parent(parent).forks(84).build();
Assert.assertEquals(Integer.valueOf(84), builder.getForkCount().get());
}
@Test
public void testGC_Empty() {
Options parent = new OptionsBuilder().build();
Options builder = new OptionsBuilder().parent(parent).build();
Assert.assertFalse(builder.shouldDoGC().hasValue());
}
@Test
public void testGC_Parent() {
Options parent = new OptionsBuilder().shouldDoGC(true).build();
Options builder = new OptionsBuilder().parent(parent).build();
Assert.assertEquals(true, builder.shouldDoGC().get());
}
@Test
public void testGC_Merge() {
Options parent = new OptionsBuilder().shouldDoGC(true).build();
Options builder = new OptionsBuilder().parent(parent).shouldDoGC(false).build();
Assert.assertEquals(false, builder.shouldDoGC().get());
}
@Test
public void testJVM_Empty() {
Options parent = new OptionsBuilder().build();
Options builder = new OptionsBuilder().parent(parent).build();
Assert.assertFalse(builder.getJvm().hasValue());
}
@Test
public void testJVM_Parent() {
Options parent = new OptionsBuilder().jvm("path").build();
Options builder = new OptionsBuilder().parent(parent).build();
Assert.assertEquals("path", builder.getJvm().get());
}
@Test
public void testJVM_Merge() {
Options parent = new OptionsBuilder().jvm("path").build();
Options builder = new OptionsBuilder().parent(parent).jvm("path2").build();
Assert.assertEquals("path2", builder.getJvm().get());
}
@Test
public void testJVMArgs_Empty() {
Options parent = new OptionsBuilder().build();
Options builder = new OptionsBuilder().parent(parent).build();
Assert.assertFalse(builder.getJvmArgs().hasValue());
}
@Test
public void testJVMArgs_Parent() {
Options parent = new OptionsBuilder().jvmArgs("opt1", "opt2").build();
Options builder = new OptionsBuilder().parent(parent).build();
Assert.assertEquals(Arrays.asList("opt1", "opt2"), builder.getJvmArgs().get());
}
@Test
public void testJVMArgs_Merge() {
Options parent = new OptionsBuilder().jvmArgs("opt1", "opt2").build();
Options builder = new OptionsBuilder().parent(parent).jvmArgs("opt3", "opt4").build();
Assert.assertEquals(Arrays.asList("opt3", "opt4"), builder.getJvmArgs().get());
}
@Test
public void testJVMArgsAppend_Empty() {
Options parent = new OptionsBuilder().build();
Options builder = new OptionsBuilder().parent(parent).build();
Assert.assertFalse(builder.getJvmArgsAppend().hasValue());
}
@Test
public void testJVMArgsAppend_Parent() {
Options parent = new OptionsBuilder().jvmArgsAppend("opt1", "opt2").build();
Options builder = new OptionsBuilder().parent(parent).build();
Assert.assertEquals(Arrays.asList("opt1", "opt2"), builder.getJvmArgsAppend().get());
}
@Test
public void testJVMArgsAppend_Merge() {
Options parent = new OptionsBuilder().jvmArgsAppend("opt1", "opt2").build();
Options builder = new OptionsBuilder().parent(parent).jvmArgsAppend("opt3", "opt4").build();
Assert.assertEquals(Arrays.asList("opt3", "opt4"), builder.getJvmArgsAppend().get());
}
@Test
public void testJVMArgsPrepend_Empty() {
Options parent = new OptionsBuilder().build();
Options builder = new OptionsBuilder().parent(parent).build();
Assert.assertFalse(builder.getJvmArgsPrepend().hasValue());
}
@Test
public void testJVMArgsPrepend_Parent() {
Options parent = new OptionsBuilder().jvmArgsPrepend("opt1", "opt2").build();
Options builder = new OptionsBuilder().parent(parent).build();
Assert.assertEquals(Arrays.asList("opt1", "opt2"), builder.getJvmArgsPrepend().get());
}
@Test
public void testJVMArgsPrepend_Merge() {
Options parent = new OptionsBuilder().jvmArgsPrepend("opt1", "opt2").build();
Options builder = new OptionsBuilder().parent(parent).jvmArgsPrepend("opt3", "opt4").build();
Assert.assertEquals(Arrays.asList("opt3", "opt4"), builder.getJvmArgsPrepend().get());
}
@Test
public void testOutput_Empty() {
Options parent = new OptionsBuilder().build();
Options builder = new OptionsBuilder().parent(parent).build();
Assert.assertFalse(builder.getOutput().hasValue());
}
@Test
public void testOutput_Parent() {
Options parent = new OptionsBuilder().output("out1").build();
Options builder = new OptionsBuilder().parent(parent).build();
Assert.assertEquals("out1", builder.getOutput().get());
}
@Test
public void testOutput_Merged() {
Options parent = new OptionsBuilder().output("out1").build();
Options builder = new OptionsBuilder().parent(parent).output("out2").build();
Assert.assertEquals("out2", builder.getOutput().get());
}
@Test
public void testResult_Empty() {
Options parent = new OptionsBuilder().build();
Options builder = new OptionsBuilder().parent(parent).build();
Assert.assertFalse(builder.getResult().hasValue());
}
@Test
public void testResult_Parent() {
Options parent = new OptionsBuilder().result("out1").build();
Options builder = new OptionsBuilder().parent(parent).build();
Assert.assertEquals("out1", builder.getResult().get());
}
@Test
public void testResult_Merged() {
Options parent = new OptionsBuilder().result("out1").build();
Options builder = new OptionsBuilder().parent(parent).result("out2").build();
Assert.assertEquals("out2", builder.getResult().get());
}
@Test
public void testResultFormat_Empty() {
Options parent = new OptionsBuilder().build();
Options builder = new OptionsBuilder().parent(parent).build();
Assert.assertFalse(builder.getResultFormat().hasValue());
}
@Test
public void testResultFormat_Parent() {
Options parent = new OptionsBuilder().resultFormat(ResultFormatType.JSON).build();
Options builder = new OptionsBuilder().parent(parent).build();
Assert.assertEquals(ResultFormatType.JSON, builder.getResultFormat().get());
}
@Test
public void testResultFormat_Merged() {
Options parent = new OptionsBuilder().resultFormat(ResultFormatType.JSON).build();
Options builder = new OptionsBuilder().parent(parent).resultFormat(ResultFormatType.SCSV).build();
Assert.assertEquals(ResultFormatType.SCSV, builder.getResultFormat().get());
}
@Test
public void testRuntime_Empty() {
Options parent = new OptionsBuilder().build();
Options builder = new OptionsBuilder().parent(parent).build();
Assert.assertFalse(builder.getMeasurementTime().hasValue());
}
@Test
public void testRuntime_Parent() {
Options parent = new OptionsBuilder().measurementTime(TimeValue.hours(42)).build();
Options builder = new OptionsBuilder().parent(parent).build();
Assert.assertEquals(TimeValue.hours(42), builder.getMeasurementTime().get());
}
@Test
public void testRuntime_Merged() {
Options parent = new OptionsBuilder().measurementTime(TimeValue.hours(42)).build();
Options builder = new OptionsBuilder().parent(parent).measurementTime(TimeValue.days(42)).build();
Assert.assertEquals(TimeValue.days(42), builder.getMeasurementTime().get());
}
@Test
public void testMeasureIters_Empty() {
Options parent = new OptionsBuilder().build();
Options builder = new OptionsBuilder().parent(parent).build();
Assert.assertFalse(builder.getMeasurementIterations().hasValue());
}
@Test
public void testMeasureIters_Parent() {
Options parent = new OptionsBuilder().measurementIterations(42).build();
Options builder = new OptionsBuilder().parent(parent).build();
Assert.assertEquals(Integer.valueOf(42), builder.getMeasurementIterations().get());
}
@Test
public void testMeasureIters_Merged() {
Options parent = new OptionsBuilder().measurementIterations(42).build();
Options builder = new OptionsBuilder().parent(parent).measurementIterations(84).build();
Assert.assertEquals(Integer.valueOf(84), builder.getMeasurementIterations().get());
}
@Test
public void testSFOE_Empty() {
Options parent = new OptionsBuilder().build();
Options builder = new OptionsBuilder().parent(parent).build();
Assert.assertFalse(builder.shouldFailOnError().hasValue());
}
@Test
public void testSFOE_Parent() {
Options parent = new OptionsBuilder().shouldFailOnError(true).build();
Options builder = new OptionsBuilder().parent(parent).build();
Assert.assertEquals(true, builder.shouldFailOnError().get());
}
@Test
public void testSFOE_Merged() {
Options parent = new OptionsBuilder().shouldFailOnError(true).build();
Options builder = new OptionsBuilder().parent(parent).shouldFailOnError(false).build();
Assert.assertEquals(false, builder.shouldFailOnError().get());
}
@Test
public void testSyncIters_Empty() {
Options parent = new OptionsBuilder().build();
Options builder = new OptionsBuilder().parent(parent).build();
Assert.assertFalse(builder.shouldSyncIterations().hasValue());
}
@Test
public void testSyncIters_Parent() {
Options parent = new OptionsBuilder().syncIterations(true).build();
Options builder = new OptionsBuilder().parent(parent).build();
Assert.assertEquals(true, builder.shouldSyncIterations().get());
}
@Test
public void testSyncIters_Merged() {
Options parent = new OptionsBuilder().syncIterations(true).build();
Options builder = new OptionsBuilder().parent(parent).syncIterations(false).build();
Assert.assertEquals(false, builder.shouldSyncIterations().get());
}
@Test
public void testThreadGroups_Empty() {
Options parent = new OptionsBuilder().build();
Options builder = new OptionsBuilder().parent(parent).build();
Assert.assertFalse(builder.getThreadGroups().hasValue());
}
@Test
public void testThreadGroups_Parent() {
Options parent = new OptionsBuilder().threadGroups(1, 2).build();
Options builder = new OptionsBuilder().parent(parent).build();
Assert.assertArrayEquals(new int[]{1, 2}, builder.getThreadGroups().get());
}
@Test
public void testThreadGroups_Merged() {
Options parent = new OptionsBuilder().threadGroups(1, 2).build();
Options builder = new OptionsBuilder().parent(parent).threadGroups(3, 4).build();
Assert.assertArrayEquals(new int[]{3, 4}, builder.getThreadGroups().get());
}
@Test
public void testThreads_Empty() {
Options parent = new OptionsBuilder().build();
Options builder = new OptionsBuilder().parent(parent).build();
Assert.assertFalse(builder.getThreads().hasValue());
}
@Test
public void testThreads_Parent() {
Options parent = new OptionsBuilder().threads(42).build();
Options builder = new OptionsBuilder().parent(parent).build();
Assert.assertEquals(Integer.valueOf(42), builder.getThreads().get());
}
@Test
public void testThreads_Merged() {
Options parent = new OptionsBuilder().threads(42).build();
Options builder = new OptionsBuilder().parent(parent).threads(84).build();
Assert.assertEquals(Integer.valueOf(84), builder.getThreads().get());
}
@Test
public void testTimeUnit_Empty() {
Options parent = new OptionsBuilder().build();
Options builder = new OptionsBuilder().parent(parent).build();
Assert.assertFalse(builder.getTimeUnit().hasValue());
}
@Test
public void testTimeUnit_Parent() {
Options parent = new OptionsBuilder().timeUnit(TimeUnit.DAYS).build();
Options builder = new OptionsBuilder().parent(parent).build();
Assert.assertEquals(TimeUnit.DAYS, builder.getTimeUnit().get());
}
@Test
public void testTimeUnit_Merged() {
Options parent = new OptionsBuilder().timeUnit(TimeUnit.DAYS).build();
Options builder = new OptionsBuilder().parent(parent).timeUnit(TimeUnit.HOURS).build();
Assert.assertEquals(TimeUnit.HOURS, builder.getTimeUnit().get());
}
@Test
public void testOPI_Empty() {
Options parent = new OptionsBuilder().build();
Options builder = new OptionsBuilder().parent(parent).build();
Assert.assertFalse(builder.getOperationsPerInvocation().hasValue());
}
@Test
public void testOPI_Parent() {
Options parent = new OptionsBuilder().operationsPerInvocation(42).build();
Options builder = new OptionsBuilder().parent(parent).build();
Assert.assertEquals(Integer.valueOf(42), builder.getOperationsPerInvocation().get());
}
@Test
public void testOPI_Merged() {
Options parent = new OptionsBuilder().operationsPerInvocation(42).build();
Options builder = new OptionsBuilder().parent(parent).operationsPerInvocation(43).build();
Assert.assertEquals(Integer.valueOf(43), builder.getOperationsPerInvocation().get());
}
@Test
public void testVerbose_Empty() {
Options parent = new OptionsBuilder().build();
Options builder = new OptionsBuilder().parent(parent).build();
Assert.assertFalse(builder.verbosity().hasValue());
}
@Test
public void testVerbose_Parent() {
Options parent = new OptionsBuilder().verbosity(VerboseMode.EXTRA).build();
Options builder = new OptionsBuilder().parent(parent).build();
Assert.assertEquals(VerboseMode.EXTRA, builder.verbosity().get());
}
@Test
public void testVerbose_Merged() {
Options parent = new OptionsBuilder().verbosity(VerboseMode.EXTRA).build();
Options builder = new OptionsBuilder().parent(parent).verbosity(VerboseMode.SILENT).build();
Assert.assertEquals(VerboseMode.SILENT, builder.verbosity().get());
}
@Test
public void testWarmupForks_Empty() {
Options parent = new OptionsBuilder().build();
Options builder = new OptionsBuilder().parent(parent).build();
Assert.assertFalse(builder.getWarmupForkCount().hasValue());
}
@Test
public void testWarmupForks_Parent() {
Options parent = new OptionsBuilder().warmupForks(42).build();
Options builder = new OptionsBuilder().parent(parent).build();
Assert.assertEquals(Integer.valueOf(42), builder.getWarmupForkCount().get());
}
@Test
public void testWarmupForks_Merge() {
Options parent = new OptionsBuilder().warmupForks(42).build();
Options builder = new OptionsBuilder().parent(parent).warmupForks(84).build();
Assert.assertEquals(Integer.valueOf(84), builder.getWarmupForkCount().get());
}
@Test
public void testWarmupIters_Empty() {
Options parent = new OptionsBuilder().build();
Options builder = new OptionsBuilder().parent(parent).build();
Assert.assertFalse(builder.getWarmupIterations().hasValue());
}
@Test
public void testWarmupIters_Parent() {
Options parent = new OptionsBuilder().warmupIterations(42).build();
Options builder = new OptionsBuilder().parent(parent).build();
Assert.assertEquals(Integer.valueOf(42), builder.getWarmupIterations().get());
}
@Test
public void testWarmupIters_Merged() {
Options parent = new OptionsBuilder().warmupIterations(42).build();
Options builder = new OptionsBuilder().parent(parent).warmupIterations(84).build();
Assert.assertEquals(Integer.valueOf(84), builder.getWarmupIterations().get());
}
@Test
public void testWarmupTime_Empty() {
Options parent = new OptionsBuilder().build();
Options builder = new OptionsBuilder().parent(parent).build();
Assert.assertFalse(builder.getWarmupTime().hasValue());
}
@Test
public void testWarmupTime_Parent() {
Options parent = new OptionsBuilder().warmupTime(TimeValue.hours(42)).build();
Options builder = new OptionsBuilder().parent(parent).build();
Assert.assertEquals(TimeValue.hours(42), builder.getWarmupTime().get());
}
@Test
public void testWarmupTime_Merged() {
Options parent = new OptionsBuilder().warmupTime(TimeValue.hours(42)).build();
Options builder = new OptionsBuilder().parent(parent).warmupTime(TimeValue.days(42)).build();
Assert.assertEquals(TimeValue.days(42), builder.getWarmupTime().get());
}
@Test
public void testWarmupMicros_Empty() {
Options parent = new OptionsBuilder().build();
Options builder = new OptionsBuilder().parent(parent).build();
Assert.assertTrue(builder.getWarmupIncludes().isEmpty());
}
@Test
public void testWarmupMicros_Parent() {
Options parent = new OptionsBuilder().includeWarmup(".*").build();
Options builder = new OptionsBuilder().parent(parent).build();
Assert.assertEquals(Collections.singletonList(".*"), builder.getWarmupIncludes());
}
@Test
public void testWarmupMicros_Merged() {
Options parent = new OptionsBuilder().includeWarmup(".*").build();
Options builder = new OptionsBuilder().parent(parent).includeWarmup(".*test.*").build();
Assert.assertEquals(Arrays.asList(".*test.*", ".*"), builder.getWarmupIncludes());
}
@Test
public void testParameters_Empty() {
Options parent = new OptionsBuilder().build();
Options builder = new OptionsBuilder().parent(parent).build();
Assert.assertFalse(builder.getParameter("x").hasValue());
}
@Test
public void testParameters_Parent() {
Options parent = new OptionsBuilder().param("x", "1", "2", "3").build();
Options builder = new OptionsBuilder().parent(parent).build();
Collection<String> bp = builder.getParameter("x").get();
Assert.assertEquals(3, bp.size());
for (String b : new String[] {"1", "2", "3"}) {
Assert.assertTrue("BP does not contain: " + b, bp.contains(b));
}
}
@Test
public void testParameters_Merged() {
Options parent = new OptionsBuilder().param("x", "1", "2", "3").build();
Options builder = new OptionsBuilder().parent(parent).param("x", "4", "5", "6").build();
Collection<String> bp = builder.getParameter("x").get();
Assert.assertEquals(3, bp.size());
for (String b : new String[] {"4", "5", "6"}) {
Assert.assertTrue("BP does not contain: " + b, bp.contains(b));
}
}
@Test
public void testTimeout_Empty() {
Options parent = new OptionsBuilder().build();
Options builder = new OptionsBuilder().parent(parent).build();
Assert.assertFalse(builder.getTimeout().hasValue());
}
@Test
public void testTimeout_Parent() {
Options parent = new OptionsBuilder().timeout(TimeValue.hours(42)).build();
Options builder = new OptionsBuilder().parent(parent).build();
Assert.assertEquals(TimeValue.hours(42), builder.getTimeout().get());
}
@Test
public void testTimeout_Merged() {
Options parent = new OptionsBuilder().timeout(TimeValue.hours(42)).build();
Options builder = new OptionsBuilder().parent(parent).timeout(TimeValue.days(42)).build();
Assert.assertEquals(TimeValue.days(42), builder.getTimeout().get());
}
}
| 25,744 | 39.226563 | 106 | java |
jmh | jmh-master/jmh-core/src/test/java/org/openjdk/jmh/runner/parameters/TimeValueTest.java | /*
* Copyright (c) 2005, 2014, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package org.openjdk.jmh.runner.parameters;
import org.junit.Assert;
import org.junit.Test;
import org.openjdk.jmh.runner.options.TimeValue;
import java.util.concurrent.TimeUnit;
public class TimeValueTest {
@Test
public void testNano() {
TimeValue v = TimeValue.fromString(TimeValue.nanoseconds(10).toString());
Assert.assertEquals(TimeUnit.NANOSECONDS, v.getTimeUnit());
Assert.assertEquals(10, v.getTime());
}
@Test
public void testMicro() {
TimeValue v = TimeValue.fromString(TimeValue.microseconds(10).toString());
Assert.assertEquals(TimeUnit.MICROSECONDS, v.getTimeUnit());
Assert.assertEquals(10, v.getTime());
}
@Test
public void testMilli() {
TimeValue v = TimeValue.fromString(TimeValue.milliseconds(10).toString());
Assert.assertEquals(TimeUnit.MILLISECONDS, v.getTimeUnit());
Assert.assertEquals(10, v.getTime());
}
@Test
public void testSeconds() {
TimeValue v = TimeValue.fromString(TimeValue.seconds(10).toString());
Assert.assertEquals(TimeUnit.SECONDS, v.getTimeUnit());
Assert.assertEquals(10, v.getTime());
}
@Test
public void testMinutes() {
TimeValue v = TimeValue.fromString(TimeValue.minutes(10).toString());
Assert.assertEquals(TimeUnit.MINUTES, v.getTimeUnit());
Assert.assertEquals(10, v.getTime());
}
@Test
public void testHours() {
TimeValue v = TimeValue.fromString(TimeValue.hours(10).toString());
Assert.assertEquals(TimeUnit.HOURS, v.getTimeUnit());
Assert.assertEquals(10, v.getTime());
}
@Test
public void testDays() {
TimeValue v = TimeValue.fromString(TimeValue.days(10).toString());
Assert.assertEquals(TimeUnit.DAYS, v.getTimeUnit());
Assert.assertEquals(10, v.getTime());
}
}
| 3,091 | 35.376471 | 82 | java |
jmh | jmh-master/jmh-core/src/test/java/org/openjdk/jmh/util/BoundedPriorityQueueTest.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.util.Collections;
import java.util.Queue;
public class BoundedPriorityQueueTest {
@Test
public void top3Smallest() {
Queue<Integer> queue = new BoundedPriorityQueue<>(3);
queue.add(50);
queue.add(40);
queue.add(10);
queue.add(20);
queue.add(30);
queue.add(30);
queue.add(80);
Assert.assertEquals(3, queue.size());
Assert.assertEquals((Integer) 30, queue.poll());
Assert.assertEquals((Integer) 20, queue.poll());
Assert.assertEquals((Integer) 10, queue.poll());
}
@Test
public void top3Largest() {
Queue<Integer> queue = new BoundedPriorityQueue<>(3, Collections.reverseOrder());
queue.add(50);
queue.add(40);
queue.add(10);
queue.add(20);
queue.add(30);
queue.add(30);
queue.add(80);
Assert.assertEquals(3, queue.size());
Assert.assertEquals((Integer) 40, queue.poll());
Assert.assertEquals((Integer) 50, queue.poll());
Assert.assertEquals((Integer) 80, queue.poll());
}
}
| 2,399 | 33.782609 | 89 | java |
jmh | jmh-master/jmh-core/src/test/java/org/openjdk/jmh/util/MultisetTest.java | /*
* Copyright (c) 2022, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package org.openjdk.jmh.util;
import static org.junit.Assert.*;
import org.junit.Test;
public class MultisetTest {
@Test
public void testClear() {
Multiset<String> set = new HashMultiset<>();
set.add("one");
set.add("two", 2);
assertFalse(set.isEmpty());
assertEquals(3, set.size());
assertEquals(2, set.keys().size());
assertEquals(1, set.count("one"));
assertEquals(2, set.count("two"));
// clear the set
set.clear();
assertTrue(set.isEmpty());
assertEquals(0, set.size());
assertEquals(0, set.keys().size());
assertEquals(0, set.count("one"));
assertEquals(0, set.count("two"));
// reuse the set
set.add("one");
set.add("two", 2);
assertFalse(set.isEmpty());
assertEquals(3, set.size());
assertEquals(2, set.keys().size());
assertEquals(1, set.count("one"));
assertEquals(2, set.count("two"));
}
}
| 2,208 | 35.816667 | 76 | java |
jmh | jmh-master/jmh-core/src/test/java/org/openjdk/jmh/util/MultisetsTest.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.util.List;
public class MultisetsTest {
@Test
public void testCountHighest() {
Multiset<Integer> set = new HashMultiset<>();
set.add(10);
set.add(10);
set.add(10);
set.add(20);
set.add(20);
set.add(70);
List<Integer> topInts = Multisets.countHighest(set, 2);
Assert.assertEquals(2, topInts.size());
Assert.assertEquals((Integer) 10, topInts.get(0));
Assert.assertEquals((Integer) 20, topInts.get(1));
}
@Test
public void testCountHighest_2() {
// Regression test for CODETOOLS-7901411
Multiset<String> set = new HashMultiset<>();
set.add("Meh", 85);
set.add("Blah", 17);
set.add("Choo", 1);
List<String> top = Multisets.countHighest(set, 3);
Assert.assertEquals(3, top.size());
Assert.assertEquals("Meh", top.get(0));
Assert.assertEquals("Blah", top.get(1));
Assert.assertEquals("Choo", top.get(2));
}
@Test
public void testSortedDesc() {
Multiset<Integer> set = new HashMultiset<>();
set.add(10);
set.add(10);
set.add(10);
set.add(20);
set.add(20);
set.add(70);
List<Integer> topInts = Multisets.sortedDesc(set);
Assert.assertEquals(3, topInts.size());
Assert.assertEquals((Integer) 10, topInts.get(0));
Assert.assertEquals((Integer) 20, topInts.get(1));
Assert.assertEquals((Integer) 70, topInts.get(2));
}
}
| 2,824 | 33.036145 | 79 | java |
jmh | jmh-master/jmh-core/src/test/java/org/openjdk/jmh/util/TestClassUtils.java | /*
* Copyright (c) 2005, 2013, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package org.openjdk.jmh.util;
import org.junit.Assert;
import org.junit.Test;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Map;
public class TestClassUtils {
@Test
public void testDenseClasses1() {
List<String> src = Arrays.asList("org.openjdk.benches.ForkJoinTest.test1", "org.openjdk.benches.ForkJoinTest.test2", "org.openjdk.benches.AnotherTest.test0");
Map<String,String> map = ClassUtils.denseClassNames(src);
Assert.assertEquals("ForkJoinTest.test1", map.get("org.openjdk.benches.ForkJoinTest.test1"));
Assert.assertEquals("ForkJoinTest.test2", map.get("org.openjdk.benches.ForkJoinTest.test2"));
}
@Test
public void testDenseClasses2() {
List<String> src = Collections.singletonList("org.openjdk.benches.ForkJoinTest.test1");
Map<String,String> map = ClassUtils.denseClassNames(src);
Assert.assertEquals("ForkJoinTest.test1", map.get("org.openjdk.benches.ForkJoinTest.test1"));
}
@Test
public void testDenseClasses3() {
List<String> src = Collections.singletonList("org.openjdk.benches.ForkJoinTest.test1:label1");
Map<String,String> map = ClassUtils.denseClassNames(src);
Assert.assertEquals("ForkJoinTest.test1:label1", map.get("org.openjdk.benches.ForkJoinTest.test1:label1"));
}
@Test
public void testDifferentPackages() {
List<String> src = Arrays.asList("com.some.even.longer.word.SomeEvenMoreWeirdBenchmark", "my.sample.pkg.MySampleBenchmark", "test.jmh.TestJmhBenchmark");
Map<String,String> map = ClassUtils.denseClassNames(src);
Assert.assertEquals("com.some.even.longer.word.SomeEvenMoreWeirdBenchmark", map.get("com.some.even.longer.word.SomeEvenMoreWeirdBenchmark"));
Assert.assertEquals("my.sample.pkg.MySampleBenchmark", map.get("my.sample.pkg.MySampleBenchmark"));
Assert.assertEquals("test.jmh.TestJmhBenchmark", map.get("test.jmh.TestJmhBenchmark"));
}
@Test
public void testSemiDifferentPackages() {
List<String> src = Arrays.asList("com.some.Benchmark", "com.some2.Benchmark2");
Map<String,String> map = ClassUtils.denseClassNames(src);
Assert.assertEquals("c.some.Benchmark", map.get("com.some.Benchmark"));
Assert.assertEquals("c.some2.Benchmark2", map.get("com.some2.Benchmark2"));
}
}
| 3,606 | 42.457831 | 166 | java |
jmh | jmh-master/jmh-core/src/test/java/org/openjdk/jmh/util/TestFileUtils.java | /*
* Copyright (c) 2005, 2013, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package org.openjdk.jmh.util;
import org.junit.Test;
import java.io.File;
import static org.junit.Assert.assertTrue;
/**
* Test for FileUtils
*/
public class TestFileUtils {
@Test
public void testExtractFromResource() throws Exception {
File test = FileUtils.extractFromResource("/org/openjdk/jmh/results/format/output-golden.json");
test.deleteOnExit();
assertTrue(test.exists());
}
}
| 1,642 | 35.511111 | 104 | java |
jmh | jmh-master/jmh-core/src/test/java/org/openjdk/jmh/util/TestListStatistics.java | /*
* Copyright (c) 2005, 2013, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package org.openjdk.jmh.util;
import org.junit.Assert;
import org.junit.BeforeClass;
import org.junit.Test;
import java.util.Iterator;
import java.util.Map;
import java.util.NoSuchElementException;
import static org.junit.Assert.assertEquals;
/**
* Tests for Statistics
*/
public class TestListStatistics {
private static final double[] VALUES = {
60.89053178, 3.589312005, 42.73638635, 85.55397805, 96.66786311,
29.31809699, 63.50268147, 52.24157468, 64.68049085, 2.34517545,
92.62435741, 7.50775664, 31.92395987, 82.68609724, 71.07171954,
15.78967174, 34.43339987, 65.40063304, 69.86288638, 22.55130769,
36.99130073, 60.17648239, 33.1484382, 56.4605944, 93.67454206
};
private static final double ASSERT_ACCURACY = 0.0000000001;
private static final ListStatistics instance = new ListStatistics();
@BeforeClass
public static void setUpClass() {
for (double value : VALUES) {
instance.addValue(value);
}
}
/**
* Test of add method, of class Statistics.
*/
@Test
public strictfp void testAdd_double() {
ListStatistics stats = new ListStatistics();
stats.addValue(VALUES[0]);
assertEquals(1, stats.getN());
assertEquals(VALUES[0], stats.getSum(), 0.0);
assertEquals(VALUES[0], stats.getMax(), 0.0);
assertEquals(VALUES[0], stats.getMin(), 0.0);
assertEquals(VALUES[0], stats.getMean(), 0.0);
assertEquals(Double.NaN, stats.getVariance(), 0.0);
assertEquals(Double.NaN, stats.getStandardDeviation(), 0.0);
}
/**
* Test of getN method, of class Statistics.
*/
@Test
public strictfp void testGetN() {
assertEquals(VALUES.length, instance.getN());
}
/**
* Test of getSum method, of class Statistics.
*/
@Test
public strictfp void testGetSum() {
assertEquals(1275.829, instance.getSum(), 0.001);
}
/**
* Test of getMean method, of class Statistics.
*/
@Test
public strictfp void testGetMean() {
assertEquals(51.033, instance.getMean(), 0.001);
}
/**
* Test of getMax method, of class Statistics.
*/
@Test
public strictfp void testGetMax() {
assertEquals(96.66786311, instance.getMax(), 0.0);
}
/**
* Test of getMin method, of class Statistics.
*/
@Test
public strictfp void testGetMin() {
assertEquals(2.34517545, instance.getMin(), 0.0);
}
/**
* Test of getVariance method, of class Statistics.
*/
@Test
public strictfp void testGetVariance() {
assertEquals(816.9807, instance.getVariance(), 0.0001);
}
/**
* Test of getStandardDeviation method, of class Statistics.
*/
@Test
public strictfp void testGetStandardDeviation() {
assertEquals(28.5828, instance.getStandardDeviation(), 0.0001);
}
/**
* Test of getConfidenceIntervalAt, of class Statistics
*/
@Test
public strictfp void testGetConfidenceInterval() {
double[] interval = instance.getConfidenceIntervalAt(0.999);
assertEquals(29.62232, interval[0], 0.002);
assertEquals(72.44402, interval[1], 0.002);
}
@Test
public strictfp void testPercentile_00() {
assertEquals(2.345, instance.getPercentile(0), 0.002);
}
@Test
public strictfp void testPercentile_50() {
assertEquals(56.460, instance.getPercentile(50), 0.002);
}
@Test
public strictfp void testPercentile_90() {
assertEquals(93.044, instance.getPercentile(90), 0.002);
}
@Test
public strictfp void testPercentile_99() {
assertEquals(96.667, instance.getPercentile(99), 0.002);
}
@Test
public strictfp void testPercentile_100() {
assertEquals(96.667, instance.getPercentile(100), 0.002);
}
/**
* Test of toString, of class Statistics
*/
@Test
public strictfp void testToString() {
String expResult = "N:25 Mean: 51.03316951740001 Min: 2.34517545 Max: 96.66786311 StdDev: 28.582874479178013";
String result = instance.toString();
assertEquals(expResult, result);
}
@Test
public strictfp void testSignificant_Always() {
ListStatistics s1 = new ListStatistics();
ListStatistics s2 = new ListStatistics();
for (int c = 0; c < 10; c++) {
s1.addValue(1);
s1.addValue(1.1);
s2.addValue(2);
s2.addValue(2.1);
}
for (double conf : new double[] {0.5, 0.9, 0.99, 0.999, 0.9999, 0.99999}) {
Assert.assertTrue("Diff significant at " + conf, s1.isDifferent(s2, conf));
Assert.assertTrue(s1.compareTo(s2, conf) < 0);
}
}
@Test
public strictfp void testSignificant_Never() {
ListStatistics s1 = new ListStatistics();
ListStatistics s2 = new ListStatistics();
for (int c = 0; c < 10; c++) {
s1.addValue(1);
s1.addValue(1.1);
s2.addValue(1);
s2.addValue(1.1);
}
for (double conf : new double[] {0.5, 0.9, 0.99, 0.999, 0.9999, 0.99999}) {
Assert.assertFalse("Diff not significant at " + conf, s1.isDifferent(s2, conf));
Assert.assertEquals(0, s1.compareTo(s2, conf));
}
}
@Test
public strictfp void testSignificant_Sometimes() {
ListStatistics s1 = new ListStatistics();
ListStatistics s2 = new ListStatistics();
for (int c = 0; c < 10; c++) {
s1.addValue(1);
s1.addValue(2);
s2.addValue(1);
s2.addValue(3);
}
Assert.assertTrue("Diff significant at 0.5", s1.isDifferent(s2, 0.5));
Assert.assertTrue("Diff significant at 0.9", s1.isDifferent(s2, 0.9));
Assert.assertFalse("Diff not significant at 0.99", s1.isDifferent(s2, 0.99));
Assert.assertFalse("Diff not significant at 0.999", s1.isDifferent(s2, 0.999));
Assert.assertFalse("Diff not significant at 0.9999", s1.isDifferent(s2, 0.9999));
Assert.assertTrue("compareTo at 0.5", s1.compareTo(s2, 0.5) < 0);
Assert.assertTrue("compareTo at 0.9", s1.compareTo(s2, 0.9) < 0);
Assert.assertEquals("compareTo at 0.99", 0, s1.compareTo(s2, 0.99));
Assert.assertEquals("compareTo at 0.999", 0, s1.compareTo(s2, 0.999));
Assert.assertEquals("compareTo at 0.9999", 0, s1.compareTo(s2, 0.9999));
}
@Test
public strictfp void testEmpty() {
Statistics s = new ListStatistics();
Assert.assertEquals(0, s.getN());
Assert.assertEquals(Double.NaN, s.getSum(), ASSERT_ACCURACY);
Assert.assertEquals(Double.NaN, s.getMin(), ASSERT_ACCURACY);
Assert.assertEquals(Double.NaN, s.getMax(), ASSERT_ACCURACY);
Assert.assertEquals(Double.NaN, s.getMean(), ASSERT_ACCURACY);
Assert.assertEquals(Double.NaN, s.getMeanErrorAt(0.5), ASSERT_ACCURACY);
Assert.assertEquals(Double.NaN, s.getVariance(), ASSERT_ACCURACY);
Assert.assertEquals(Double.NaN, s.getStandardDeviation(), ASSERT_ACCURACY);
Assert.assertEquals(Double.NaN, s.getConfidenceIntervalAt(0.50)[0], ASSERT_ACCURACY);
Assert.assertEquals(Double.NaN, s.getConfidenceIntervalAt(0.50)[1], ASSERT_ACCURACY);
Assert.assertEquals(Double.NaN, s.getPercentile(0), ASSERT_ACCURACY);
Assert.assertEquals(Double.NaN, s.getPercentile(100), ASSERT_ACCURACY);
}
@Test
public strictfp void testSingle() {
ListStatistics s = new ListStatistics();
s.addValue(42.0D);
Assert.assertEquals(1, s.getN());
Assert.assertEquals(42.0D, s.getSum(), ASSERT_ACCURACY);
Assert.assertEquals(42.0D, s.getMin(), ASSERT_ACCURACY);
Assert.assertEquals(42.0D, s.getMax(), ASSERT_ACCURACY);
Assert.assertEquals(42.0D, s.getMean(), ASSERT_ACCURACY);
Assert.assertEquals(Double.NaN, s.getMeanErrorAt(0.5), ASSERT_ACCURACY);
Assert.assertEquals(Double.NaN, s.getVariance(), ASSERT_ACCURACY);
Assert.assertEquals(Double.NaN, s.getStandardDeviation(), ASSERT_ACCURACY);
Assert.assertEquals(Double.NaN, s.getConfidenceIntervalAt(0.50)[0], ASSERT_ACCURACY);
Assert.assertEquals(Double.NaN, s.getConfidenceIntervalAt(0.50)[1], ASSERT_ACCURACY);
Assert.assertEquals(42.0D, s.getPercentile(0), ASSERT_ACCURACY);
Assert.assertEquals(42.0D, s.getPercentile(100), ASSERT_ACCURACY);
}
@Test
public strictfp void testHistogram_MinMax() {
ListStatistics s = new ListStatistics();
s.addValue(42.5);
Util.assertHistogram(s,
new double[] {Double.MIN_VALUE, Double.MAX_VALUE},
new int[] {1}
);
}
@Test
public strictfp void testHistogram_42_43() {
ListStatistics s = new ListStatistics();
s.addValue(42.5);
Util.assertHistogram(s,
new double[] {42, 43},
new int[] {1}
);
}
@Test
public strictfp void testHistogram_0_42() {
ListStatistics s = new ListStatistics();
s.addValue(42.5);
Util.assertHistogram(s,
new double[] {0, 42},
new int[] {0}
);
}
@Test
public strictfp void testHistogram_43_100() {
ListStatistics s = new ListStatistics();
s.addValue(42.5);
Util.assertHistogram(s,
new double[] {43, 100},
new int[] {0}
);
}
@Test
public strictfp void testHistogram_leftBound() {
ListStatistics s = new ListStatistics();
s.addValue(10);
Util.assertHistogram(s,
new double[] {10, 100},
new int[] {1}
);
}
@Test
public strictfp void testHistogram_rightBound() {
ListStatistics s = new ListStatistics();
s.addValue(10);
Util.assertHistogram(s,
new double[] {0, 10},
new int[] {0}
);
}
@Test
public strictfp void testHistogram_emptyLevels_left() {
ListStatistics s = new ListStatistics();
s.addValue(9);
Util.assertHistogram(s,
new double[] {0, 2, 4, 8, 10},
new int[] {0, 0, 0, 1}
);
}
@Test
public strictfp void testHistogram_emptyLevels_right() {
ListStatistics s = new ListStatistics();
s.addValue(1);
Util.assertHistogram(s,
new double[] {0, 2, 4, 8, 10},
new int[] {1, 0, 0, 0}
);
}
@Test
public strictfp void testHistogram_emptyLevels_middle() {
ListStatistics s = new ListStatistics();
s.addValue(5);
Util.assertHistogram(s,
new double[] {0, 2, 4, 8, 10},
new int[] {0, 0, 1, 0}
);
}
@Test
public strictfp void testHistogram_increasing() {
ListStatistics s = new ListStatistics();
for (int c = 0; c <= 10; c++) {
for (int t = 0; t < c; t++) {
s.addValue(c * 10);
}
}
Util.assertHistogram(s,
new double[] {0, 200},
new int[] {55}
);
Util.assertHistogram(s,
new double[] {0, 50, 101},
new int[] {10, 45}
);
Util.assertHistogram(s,
new double[] {0, 10, 20, 30, 40, 50, 60, 70, 80, 90, 100},
new int[] {0, 1, 2, 3, 4, 5, 6, 7, 8, 9}
);
}
/**
* Test of iterator which make accessible raw data.
*/
@Test
public strictfp void testRawDataIterator() {
Iterator<Map.Entry<Double, Long>> listIter = instance.getRawData();
for (double item : VALUES) {
Assert.assertTrue(listIter.hasNext());
Map.Entry<Double, Long> entry = listIter.next();
Assert.assertEquals(entry.getKey(), item, ASSERT_ACCURACY);
Assert.assertEquals(1L, entry.getValue().longValue());
}
Assert.assertFalse(listIter.hasNext());
try {
listIter.next();
Assert.fail("Expected NoSuchElementException");
} catch (NoSuchElementException e) {
// expected
}
}
}
| 13,586 | 31.044811 | 118 | java |
jmh | jmh-master/jmh-core/src/test/java/org/openjdk/jmh/util/TestMultisetStatistics.java | /*
* Copyright (c) 2005, 2013, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package org.openjdk.jmh.util;
import org.junit.Assert;
import org.junit.BeforeClass;
import org.junit.Test;
import java.util.Iterator;
import java.util.Map;
import java.util.NoSuchElementException;
import static org.junit.Assert.assertEquals;
/**
* Tests for Statistics
*/
public class TestMultisetStatistics {
private static final double[] VALUES = {
60.89053178, 3.589312005, 42.73638635, 85.55397805, 96.66786311,
29.31809699, 63.50268147, 52.24157468, 64.68049085, 2.34517545,
92.62435741, 7.50775664, 31.92395987, 82.68609724, 71.07171954,
15.78967174, 34.43339987, 65.40063304, 69.86288638, 22.55130769,
36.99130073, 60.17648239, 33.1484382, 56.4605944, 93.67454206
};
private static final double ASSERT_ACCURACY = 0.000000001;
private static final MultisetStatistics instance = new MultisetStatistics();
@BeforeClass
public static void setUpClass() {
for (double value : VALUES) {
instance.addValue(value, 1);
}
}
/**
* Test of add method, of class Statistics.
*/
@Test
public strictfp void testAdd_double() {
MultisetStatistics stats = new MultisetStatistics();
stats.addValue(VALUES[0], 1);
assertEquals(1, stats.getN());
assertEquals(VALUES[0], stats.getSum(), 0.0);
assertEquals(VALUES[0], stats.getMax(), 0.0);
assertEquals(VALUES[0], stats.getMin(), 0.0);
assertEquals(VALUES[0], stats.getMean(), 0.0);
assertEquals(Double.NaN, stats.getVariance(), 0.0);
assertEquals(Double.NaN, stats.getStandardDeviation(), 0.0);
}
/**
* Test of getN method, of class Statistics.
*/
@Test
public strictfp void testGetN() {
assertEquals(VALUES.length, instance.getN());
}
/**
* Test of getSum method, of class Statistics.
*/
@Test
public strictfp void testGetSum() {
assertEquals(1275.829, instance.getSum(), 0.001);
}
/**
* Test of getMean method, of class Statistics.
*/
@Test
public strictfp void testGetMean() {
assertEquals(51.033, instance.getMean(), 0.001);
}
/**
* Test of getMax method, of class Statistics.
*/
@Test
public strictfp void testGetMax() {
assertEquals(96.66786311, instance.getMax(), 0.0);
}
/**
* Test of getMin method, of class Statistics.
*/
@Test
public strictfp void testGetMin() {
assertEquals(2.34517545, instance.getMin(), 0.0);
}
/**
* Test of getVariance method, of class Statistics.
*/
@Test
public strictfp void testGetVariance() {
assertEquals(816.9807, instance.getVariance(), 0.0001);
}
/**
* Test of getStandardDeviation method, of class Statistics.
*/
@Test
public strictfp void testGetStandardDeviation() {
assertEquals(28.5828, instance.getStandardDeviation(), 0.0001);
}
/**
* Test of getConfidenceIntervalAt, of class Statistics
*/
@Test
public strictfp void testGetConfidenceInterval() {
double[] interval = instance.getConfidenceIntervalAt(0.999);
assertEquals(29.62232, interval[0], 0.002);
assertEquals(72.44402, interval[1], 0.002);
}
@Test
public strictfp void testPercentile_00() {
assertEquals(2.345, instance.getPercentile(0), 0.002);
}
@Test
public strictfp void testPercentile_50() {
assertEquals(56.460, instance.getPercentile(50), 0.002);
}
@Test
public strictfp void testPercentile_90() {
assertEquals(93.044, instance.getPercentile(90), 0.002);
}
@Test
public strictfp void testPercentile_99() {
assertEquals(96.667, instance.getPercentile(99), 0.002);
}
@Test
public strictfp void testPercentile_100() {
assertEquals(96.667, instance.getPercentile(100), 0.002);
}
/**
* Test of toString, of class Statistics
*/
@Test
public strictfp void testToString() {
String expResult = "N:25 Mean: 51.033169517400005 Min: 2.34517545 Max: 96.66786311 StdDev: 28.582874479178017";
String result = instance.toString();
assertEquals(expResult, result);
}
@Test
public strictfp void testSignificant_Always() {
MultisetStatistics s1 = new MultisetStatistics();
MultisetStatistics s2 = new MultisetStatistics();
s1.addValue(1, 10);
s1.addValue(1.1, 10);
s2.addValue(2, 10);
s2.addValue(2.1, 10);
for (double conf : new double[] {0.5, 0.9, 0.99, 0.999, 0.9999, 0.99999}) {
Assert.assertTrue("Diff significant at " + conf, s1.isDifferent(s2, conf));
Assert.assertTrue(s1.compareTo(s2, conf) < 0);
}
}
@Test
public strictfp void testSignificant_Never() {
MultisetStatistics s1 = new MultisetStatistics();
MultisetStatistics s2 = new MultisetStatistics();
s1.addValue(1, 10);
s1.addValue(1.1, 10);
s2.addValue(1, 10);
s2.addValue(1.1, 10);
for (double conf : new double[] {0.5, 0.9, 0.99, 0.999, 0.9999, 0.99999}) {
Assert.assertFalse("Diff not significant at " + conf, s1.isDifferent(s2, conf));
Assert.assertEquals(0, s1.compareTo(s2, conf));
}
}
@Test
public strictfp void testSignificant_Sometimes() {
MultisetStatistics s1 = new MultisetStatistics();
MultisetStatistics s2 = new MultisetStatistics();
s1.addValue(1, 10);
s1.addValue(2, 10);
s2.addValue(1, 10);
s2.addValue(3, 10);
Assert.assertTrue("Diff significant at 0.5", s1.isDifferent(s2, 0.5));
Assert.assertTrue("Diff significant at 0.9", s1.isDifferent(s2, 0.9));
Assert.assertFalse("Diff not significant at 0.99", s1.isDifferent(s2, 0.99));
Assert.assertFalse("Diff not significant at 0.999", s1.isDifferent(s2, 0.999));
Assert.assertFalse("Diff not significant at 0.9999", s1.isDifferent(s2, 0.9999));
Assert.assertTrue("compareTo at 0.5", s1.compareTo(s2, 0.5) < 0);
Assert.assertTrue("compareTo at 0.9", s1.compareTo(s2, 0.9) < 0);
Assert.assertEquals("compareTo at 0.99", 0, s1.compareTo(s2, 0.99));
Assert.assertEquals("compareTo at 0.999", 0, s1.compareTo(s2, 0.999));
Assert.assertEquals("compareTo at 0.9999", 0, s1.compareTo(s2, 0.9999));
}
@Test
public strictfp void testEmpty() {
Statistics s = new MultisetStatistics();
Assert.assertEquals(0, s.getN());
Assert.assertEquals(Double.NaN, s.getSum(), ASSERT_ACCURACY);
Assert.assertEquals(Double.NaN, s.getMin(), ASSERT_ACCURACY);
Assert.assertEquals(Double.NaN, s.getMax(), ASSERT_ACCURACY);
Assert.assertEquals(Double.NaN, s.getMean(), ASSERT_ACCURACY);
Assert.assertEquals(Double.NaN, s.getMeanErrorAt(0.5), ASSERT_ACCURACY);
Assert.assertEquals(Double.NaN, s.getVariance(), ASSERT_ACCURACY);
Assert.assertEquals(Double.NaN, s.getStandardDeviation(), ASSERT_ACCURACY);
Assert.assertEquals(Double.NaN, s.getConfidenceIntervalAt(0.50)[0], ASSERT_ACCURACY);
Assert.assertEquals(Double.NaN, s.getConfidenceIntervalAt(0.50)[1], ASSERT_ACCURACY);
Assert.assertEquals(Double.NaN, s.getPercentile(0), ASSERT_ACCURACY);
Assert.assertEquals(Double.NaN, s.getPercentile(100), ASSERT_ACCURACY);
}
@Test
public strictfp void testSingle() {
MultisetStatistics s = new MultisetStatistics();
s.addValue(42.0D, 1);
Assert.assertEquals(1, s.getN());
Assert.assertEquals(42.0D, s.getSum(), ASSERT_ACCURACY);
Assert.assertEquals(42.0D, s.getMin(), ASSERT_ACCURACY);
Assert.assertEquals(42.0D, s.getMax(), ASSERT_ACCURACY);
Assert.assertEquals(42.0D, s.getMean(), ASSERT_ACCURACY);
Assert.assertEquals(Double.NaN, s.getMeanErrorAt(0.5), ASSERT_ACCURACY);
Assert.assertEquals(Double.NaN, s.getVariance(), ASSERT_ACCURACY);
Assert.assertEquals(Double.NaN, s.getStandardDeviation(), ASSERT_ACCURACY);
Assert.assertEquals(Double.NaN, s.getConfidenceIntervalAt(0.50)[0], ASSERT_ACCURACY);
Assert.assertEquals(Double.NaN, s.getConfidenceIntervalAt(0.50)[1], ASSERT_ACCURACY);
Assert.assertEquals(42.0D, s.getPercentile(0), ASSERT_ACCURACY);
Assert.assertEquals(42.0D, s.getPercentile(100), ASSERT_ACCURACY);
}
@Test
public strictfp void testHistogram_MinMax() {
MultisetStatistics s = new MultisetStatistics();
s.addValue(42.5, 1);
Util.assertHistogram(s,
new double[] {Double.MIN_VALUE, Double.MAX_VALUE},
new int[] {1}
);
}
@Test
public strictfp void testHistogram_42_43() {
MultisetStatistics s = new MultisetStatistics();
s.addValue(42.5, 1);
Util.assertHistogram(s,
new double[] {42, 43},
new int[] {1}
);
}
@Test
public strictfp void testHistogram_0_42() {
MultisetStatistics s = new MultisetStatistics();
s.addValue(42.5, 1);
Util.assertHistogram(s,
new double[] {0, 42},
new int[] {0}
);
}
@Test
public strictfp void testHistogram_43_100() {
MultisetStatistics s = new MultisetStatistics();
s.addValue(42.5, 1);
Util.assertHistogram(s,
new double[] {43, 100},
new int[] {0}
);
}
@Test
public strictfp void testHistogram_leftBound() {
MultisetStatistics s = new MultisetStatistics();
s.addValue(10, 1);
Util.assertHistogram(s,
new double[] {10, 100},
new int[] {1}
);
}
@Test
public strictfp void testHistogram_rightBound() {
MultisetStatistics s = new MultisetStatistics();
s.addValue(10, 1);
Util.assertHistogram(s,
new double[] {0, 10},
new int[] {0}
);
}
@Test
public strictfp void testHistogram_emptyLevels_left() {
MultisetStatistics s = new MultisetStatistics();
s.addValue(9, 1);
Util.assertHistogram(s,
new double[] {0, 2, 4, 8, 10},
new int[] {0, 0, 0, 1}
);
}
@Test
public strictfp void testHistogram_emptyLevels_right() {
MultisetStatistics s = new MultisetStatistics();
s.addValue(1, 1);
Util.assertHistogram(s,
new double[] {0, 2, 4, 8, 10},
new int[] {1, 0, 0, 0}
);
}
@Test
public strictfp void testHistogram_emptyLevels_middle() {
MultisetStatistics s = new MultisetStatistics();
s.addValue(5, 1);
Util.assertHistogram(s,
new double[] {0, 2, 4, 8, 10},
new int[] {0, 0, 1, 0}
);
}
@Test
public strictfp void testHistogram_increasing() {
MultisetStatistics s = new MultisetStatistics();
for (int c = 0; c <= 10; c++) {
s.addValue(c * 10, c);
}
Util.assertHistogram(s,
new double[] {0, 200},
new int[] {55}
);
Util.assertHistogram(s,
new double[] {0, 50, 101},
new int[] {10, 45}
);
Util.assertHistogram(s,
new double[] {0, 10, 20, 30, 40, 50, 60, 70, 80, 90, 100},
new int[] {0, 1, 2, 3, 4, 5, 6, 7, 8, 9}
);
}
/**
* Test of iterator which make accessible raw data.
* Iterate over default instance with no duplicates.
*/
@Test
public strictfp void testRawDataIterator_no_duplicates() {
int itemCount = 0;
Iterator<Map.Entry<Double, Long>> it = instance.getRawData();
for (Map.Entry<Double, Long> entry : Utils.adaptForLoop(it)) {
Assert.assertEquals(entry.getValue().longValue(), 1L);
// Check if key (the actual data) is in the VALUES collection,
// else fail the test (the Multiset was constructed with values
// from VALUES collection, so it should be there).
boolean keyIsPresent = false;
double key = entry.getKey();
for (double value : VALUES) {
if (Double.compare(value, key) == 0) {
keyIsPresent = true;
break;
}
}
Assert.assertTrue("Value from iterator is not present in source collection", keyIsPresent);
itemCount++;
}
Assert.assertEquals(itemCount, VALUES.length);
Assert.assertFalse(it.hasNext());
try {
it.next();
Assert.fail("Expected NoSuchElementException");
} catch (NoSuchElementException e) {
// expected
}
}
/**
* Test of iterator which make accessible raw data.
* Iterate over new instance with duplicates.
*/
@Test
public strictfp void testRawDataIterator_duplicates() {
MultisetStatistics s = new MultisetStatistics();
for (int c = 0; c <= 10; c++) {
s.addValue(c * 10, c);
}
Iterator<Map.Entry<Double, Long>> it = s.getRawData();
int itemCount = 0;
for (Map.Entry<Double, Long> entry : Utils.adaptForLoop(it)) {
Assert.assertEquals(entry.getKey(), (double)(entry.getValue() * 10), ASSERT_ACCURACY);
itemCount++;
}
Assert.assertEquals(itemCount, 10);
Assert.assertFalse(it.hasNext());
try {
it.next();
Assert.fail("Expected NoSuchElementException");
} catch (NoSuchElementException e) {
// expected
}
}
}
| 15,089 | 31.804348 | 119 | java |
jmh | jmh-master/jmh-core/src/test/java/org/openjdk/jmh/util/TestSingletonStatistics.java | /*
* Copyright (c) 2005, 2013, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package org.openjdk.jmh.util;
import org.junit.Assert;
import org.junit.BeforeClass;
import org.junit.Test;
import java.util.Iterator;
import java.util.Map;
import java.util.NoSuchElementException;
import static org.junit.Assert.assertEquals;
/**
* Tests for Statistics
*/
public class TestSingletonStatistics {
private static final double VALUE = 42.73638635;
private static final double ASSERT_ACCURACY = 0.000000001;
private static final ListStatistics listStats = new ListStatistics();
private static final SingletonStatistics singStats = new SingletonStatistics(VALUE);
@BeforeClass
public static void setUpClass() {
listStats.addValue(VALUE);
}
/**
* Test of getN method, of class Statistics.
*/
@Test
public strictfp void testGetN() {
assertEquals(listStats.getN(), singStats.getN());
}
/**
* Test of getSum method, of class Statistics.
*/
@Test
public strictfp void testGetSum() {
assertEquals(listStats.getSum(), singStats.getSum(), 0.001);
}
/**
* Test of getMean method, of class Statistics.
*/
@Test
public strictfp void testGetMean() {
assertEquals(listStats.getMean(), singStats.getMean(), 0.001);
}
/**
* Test of getMax method, of class Statistics.
*/
@Test
public strictfp void testGetMax() {
assertEquals(listStats.getMax(), singStats.getMax(), 0.001);
}
/**
* Test of getMin method, of class Statistics.
*/
@Test
public strictfp void testGetMin() {
assertEquals(listStats.getMin(), singStats.getMin(), 0.001);
}
/**
* Test of getVariance method, of class Statistics.
*/
@Test
public strictfp void testGetVariance() {
assertEquals(listStats.getVariance(), singStats.getVariance(), 0.001);
}
/**
* Test of getStandardDeviation method, of class Statistics.
*/
@Test
public strictfp void testGetStandardDeviation() {
assertEquals(listStats.getStandardDeviation(), singStats.getStandardDeviation(), 0.001);
}
/**
* Test of getConfidenceIntervalAt, of class Statistics
*/
@Test
public strictfp void testGetConfidenceInterval() {
double[] listInterval = listStats.getConfidenceIntervalAt(0.999);
double[] singInterval = singStats.getConfidenceIntervalAt(0.999);
assertEquals(listInterval[0], singInterval[0], 0.001);
assertEquals(listInterval[1], singInterval[1], 0.001);
}
@Test
public strictfp void testPercentile_00() {
assertEquals(listStats.getPercentile(0), singStats.getPercentile(0), 0.002);
}
@Test
public strictfp void testPercentile_50() {
assertEquals(listStats.getPercentile(50), singStats.getPercentile(50), 0.002);
}
@Test
public strictfp void testPercentile_90() {
assertEquals(listStats.getPercentile(90), singStats.getPercentile(90), 0.002);
}
@Test
public strictfp void testPercentile_99() {
assertEquals(listStats.getPercentile(99), singStats.getPercentile(99), 0.002);
}
@Test
public strictfp void testPercentile_100() {
assertEquals(listStats.getPercentile(100), singStats.getPercentile(100), 0.002);
}
@Test
public strictfp void testSingle() {
SingletonStatistics s = new SingletonStatistics(42.0D);
Assert.assertEquals(1, s.getN());
Assert.assertEquals(42.0D, s.getSum(), ASSERT_ACCURACY);
Assert.assertEquals(42.0D, s.getMin(), ASSERT_ACCURACY);
Assert.assertEquals(42.0D, s.getMax(), ASSERT_ACCURACY);
Assert.assertEquals(42.0D, s.getMean(), ASSERT_ACCURACY);
Assert.assertEquals(Double.NaN, s.getMeanErrorAt(0.5), ASSERT_ACCURACY);
Assert.assertEquals(Double.NaN, s.getVariance(), ASSERT_ACCURACY);
Assert.assertEquals(Double.NaN, s.getStandardDeviation(), ASSERT_ACCURACY);
Assert.assertEquals(Double.NaN, s.getConfidenceIntervalAt(0.50)[0], ASSERT_ACCURACY);
Assert.assertEquals(Double.NaN, s.getConfidenceIntervalAt(0.50)[1], ASSERT_ACCURACY);
Assert.assertEquals(42.0D, s.getPercentile(0), ASSERT_ACCURACY);
Assert.assertEquals(42.0D, s.getPercentile(100), ASSERT_ACCURACY);
}
@Test
public strictfp void testHistogram_MinMax() {
SingletonStatistics s = new SingletonStatistics(42.5);
Util.assertHistogram(s,
new double[] {Double.MIN_VALUE, Double.MAX_VALUE},
new int[] {1}
);
}
@Test
public strictfp void testHistogram_42_43() {
SingletonStatistics s = new SingletonStatistics(42.5);
Util.assertHistogram(s,
new double[] {42, 43},
new int[] {1}
);
}
@Test
public strictfp void testHistogram_0_42() {
SingletonStatistics s = new SingletonStatistics(42.5);
Util.assertHistogram(s,
new double[] {0, 42},
new int[] {0}
);
}
@Test
public strictfp void testHistogram_43_100() {
SingletonStatistics s = new SingletonStatistics(42.5);
Util.assertHistogram(s,
new double[] {43, 100},
new int[] {0}
);
}
@Test
public strictfp void testHistogram_leftBound() {
SingletonStatistics s = new SingletonStatistics(10);
Util.assertHistogram(s,
new double[] {10, 100},
new int[] {1}
);
}
@Test
public strictfp void testHistogram_rightBound() {
SingletonStatistics s = new SingletonStatistics(10);
Util.assertHistogram(s,
new double[] {0, 10},
new int[] {0}
);
}
@Test
public strictfp void testHistogram_emptyLevels_left() {
SingletonStatistics s = new SingletonStatistics(9);
Util.assertHistogram(s,
new double[] {0, 2, 4, 8, 10},
new int[] {0, 0, 0, 1}
);
}
@Test
public strictfp void testHistogram_emptyLevels_right() {
SingletonStatistics s = new SingletonStatistics(1);
Util.assertHistogram(s,
new double[] {0, 2, 4, 8, 10},
new int[] {1, 0, 0, 0}
);
}
@Test
public strictfp void testHistogram_emptyLevels_middle() {
SingletonStatistics s = new SingletonStatistics(5);
Util.assertHistogram(s,
new double[] {0, 2, 4, 8, 10},
new int[] {0, 0, 1, 0}
);
}
/**
* Test of iterator which make accessible raw data.
*/
@Test
public strictfp void testRawDataIterator() {
Iterator<Map.Entry<Double, Long>> singIter = singStats.getRawData();
Assert.assertTrue(singIter.hasNext());
Map.Entry<Double, Long> entry = singIter.next();
Assert.assertEquals(entry.getKey(), VALUE, ASSERT_ACCURACY);
Assert.assertEquals(entry.getValue().longValue(), 1L);
Assert.assertFalse(singIter.hasNext());
try {
singIter.next();
Assert.fail("Expected NoSuchElementException");
} catch (NoSuchElementException e) {
// expected
}
}
}
| 8,479 | 29.948905 | 96 | java |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.