Created
June 2, 2023 21:14
-
-
Save orbyfied/033b0d0a6aeb0741cb039a4112791f48 to your computer and use it in GitHub Desktop.
Scuffed Benchmark Runner
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.io.PrintStream; | |
import java.util.function.Consumer; | |
import java.util.function.IntConsumer; | |
public class Benchmarks { | |
public static record BenchmarkResult(String name, int maxPasses, long maxTime, | |
int passes, long totalTime, double averagePassTime) { | |
public BenchmarkResult print(PrintStream stream) { | |
long tms = totalTime / 1_000_000; | |
stream.println("+- " + name + ": " + passes + " Passes " + | |
(passes >= maxPasses ? "(MAX) " : "") + " | Total Time: " + totalTime + "ns (" + tms + "ms)" + | |
" | Avg. time/pass: " + averagePassTime + "ns (" + averagePassTime / 1_000_000 + "ms)"); | |
return this; | |
} | |
public BenchmarkResult print() { | |
return print(System.out); | |
} | |
} | |
/////////////////////////////// | |
public static BenchmarkResult performBenchmark( | |
String name, | |
IntConsumer func, | |
int maxPasses, | |
long maxTime | |
) { | |
maxPasses--; // account for i++ returning last value | |
// timing | |
long start = System.nanoTime(); | |
// do passes | |
int i = 0; | |
while ( | |
(System.nanoTime() - start) < maxTime | |
&& (i++) < maxPasses | |
) | |
func.accept(i); | |
// timings | |
long end = System.nanoTime(); | |
long tns = end - start; | |
double tpp = tns / (i * 1D); | |
// return result | |
return new BenchmarkResult( | |
name, maxPasses, maxTime, | |
i, tns, tpp | |
); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment