Skip to content

Instantly share code, notes, and snippets.

@eduhoribe
Created November 24, 2020 19:25
Show Gist options
  • Save eduhoribe/8ef93cc63f7d39083ad0fe39ff49f872 to your computer and use it in GitHub Desktop.
Save eduhoribe/8ef93cc63f7d39083ad0fe39ff49f872 to your computer and use it in GitHub Desktop.
Super simple (like an amoeba) benchmark class
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
import java.util.function.Function;
import java.util.logging.Logger;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
public class AmoebaBenchmark {
private static final Logger logger = Logger.getGlobal();
private final Map<String, Long> results = new HashMap<>();
private final Map<String, Long> runningTasks = new HashMap<>();
private final BENCHMARK_OUTPUT output;
private final File outputFile;
private final String benchmarkName;
public enum BENCHMARK_OUTPUT {
STDOUT, LOG, FILE, NONE
}
public AmoebaBenchmark() {
this(BENCHMARK_OUTPUT.LOG);
}
public AmoebaBenchmark(BENCHMARK_OUTPUT output) {
this(output, (String) null);
}
public AmoebaBenchmark(String benchmarkName) {
this(BENCHMARK_OUTPUT.LOG, benchmarkName);
}
public AmoebaBenchmark(BENCHMARK_OUTPUT output, String benchmarkName) {
this(output, null, benchmarkName);
}
public AmoebaBenchmark(BENCHMARK_OUTPUT output, File outputFile) {
this(output, outputFile, null);
}
public AmoebaBenchmark(BENCHMARK_OUTPUT output, File outputFile, String benchmarkName) {
if (BENCHMARK_OUTPUT.FILE.equals(output) && outputFile == null) {
throw new IllegalArgumentException("Output file is null");
}
this.output = output;
this.outputFile = outputFile;
this.benchmarkName = benchmarkName;
}
public void ini(String taskName) {
runningTasks.put(taskName, System.currentTimeMillis());
}
public void end(String taskName) {
long end = System.currentTimeMillis();
if (!runningTasks.containsKey(taskName)) {
throw new RuntimeException("Task with name '" + taskName + "' have not been initialized");
}
long ini = runningTasks.get(taskName);
results.put(taskName, end - ini);
}
public void plot() {
plotOnlyIf(null);
}
public void plot(String taskName) {
plotOnlyIf(taskName, null);
}
public void plotSlowerThan(long minimumTime) {
plotOnlyIf(l -> l.getValue() > minimumTime);
}
public void plotSlowerThan(String taskName, long minimumTime) {
plotOnlyIf(taskName, l -> l.getValue() > minimumTime);
}
public void plotOnlyIf(Function<Map.Entry<String, Long>, Boolean> condition) {
showBenchmarkHeader(false);
for (String key : results.keySet()) {
plotImpl(key, condition, true);
}
showBenchmarkFooter(false);
}
public void plotOnlyIf(String taskName, Function<Map.Entry<String, Long>, Boolean> condition) {
plotImpl(taskName, condition, false);
}
private void plotImpl(String taskName, Function<Map.Entry<String, Long>, Boolean> condition, boolean insideLoop) {
Map.Entry<String, Long> entry = results.entrySet().stream().filter(e -> Objects.equals(e.getKey(), taskName)).findAny().orElse(null);
if (entry == null) {
logger.warning("Task '" + taskName + "' not found");
return;
}
if (condition == null || condition.apply(entry)) {
showBenchmarkHeader(insideLoop);
log(taskName + ": " + entry.getValue() + " ms");
showBenchmarkFooter(insideLoop);
}
}
private String formattedBenchmarkName() {
return "----------[" + benchmarkName + "]---------";
}
private void showBenchmarkHeader(boolean insideLoop) {
if (!insideLoop && benchmarkName != null) {
log(formattedBenchmarkName());
}
}
private void showBenchmarkFooter(boolean insideLoop) {
if (!insideLoop && benchmarkName != null) {
String footer = IntStream.range(0, formattedBenchmarkName().length()).mapToObj(i -> "-").collect(Collectors.joining());
log(footer);
}
}
private void log(String message) {
switch (output) {
case STDOUT:
System.out.println(message);
break;
case LOG:
logger.info(message);
break;
case FILE:
logInFile(outputFile, message);
break;
default:
break;
}
}
private void logInFile(File outputFile, String message) {
try {
Path path = outputFile.toPath();
if (!outputFile.exists()) {
outputFile.createNewFile();
}
long fileSize = outputFile.length() / (1024 * 1024);
int it = 1;
while (fileSize >= 10) {
path = Paths.get(path + "-" + it);
outputFile = path.toFile();
if (!outputFile.exists()) {
outputFile.createNewFile();
}
fileSize = outputFile.length() / (1024 * 1024);
it -= -1;
}
Files.write(path, (message + System.lineSeparator()).getBytes(), StandardOpenOption.APPEND);
} catch (IOException e) {
logger.severe("ERROR TO WRITE IN BENCHMARK LOG");
logger.severe(e.getMessage());
}
}
public static void main(String[] args) throws Exception {
AmoebaBenchmark benchmark = new AmoebaBenchmark(BENCHMARK_OUTPUT.STDOUT, "BENCHMARK");
benchmark.ini("TASK 1");
benchmark.ini("TASK 2");
benchmark.ini("TASK 3");
Thread.sleep(1000);
benchmark.end("TASK 1");
Thread.sleep(1000);
benchmark.end("TASK 2");
Thread.sleep(1000);
benchmark.end("TASK 3");
benchmark.plot();
}
}
@jojulio
Copy link

jojulio commented Nov 24, 2020

First

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment