Skip to content

Instantly share code, notes, and snippets.

@tobyjoiner
Last active October 7, 2020 20:15
Show Gist options
  • Save tobyjoiner/66891e20285aaa2dac7286b210352217 to your computer and use it in GitHub Desktop.
Save tobyjoiner/66891e20285aaa2dac7286b210352217 to your computer and use it in GitHub Desktop.
Benchmark a method
function runBenchMark($method, $runs){
$time_start = microtime(true);
for( $i=0; $i <= $runs; $i++){
$method();
}
$time_end = microtime(true);
return (float)($time_end - $time_start);
}
function benchMark($method1, $method2, $runs){
$first = runBenchMark($method1, $runs);
$second = runBenchMark($method2, $runs);
echo "First run: $first\n\r";
echo "Second run: $second\n\r";
if ($first < $second){
$time = $second - $first;
return 'First method is faster than the second method by: ' . $time . ' seconds. Runs: ' . $runs;
} elseif($first > $second) {
$time = $first - $second;
return 'Second method is faster than the first method by: ' . $time . ' seconds. Runs: ' . $runs;
} else {
return 'First and Second Method take the same amount of time to run';
}
}
function methodOne() {
$items = [30,59];
App\Product::whereIn('id', $items)->get();
}
function methodTwo() {
$items = [30,59];
App\Product::find($items);
}
$runs = 10000;
echo benchMark('methodOne', 'methodTwo', $runs);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment