Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
PHP / Laravel 5 Benchmark Tool
<?php
namespace App;
class Benchmark {
private static $_times = [];
private static $_last_time = null;
private static $_last_name = null;
public static function run ($name = 'Unnamed Test') {
if (!isset(static::$_times[$name]))
static::$_times[$name] = [];
if (!is_null(static::$_last_name)) {
$now = microtime(true);
$time = $now - static::$_last_time;
static::$_times[static::$_last_name][] = $time;
}
if (is_null($name))
return;
static::$_last_name = $name;
static::$_last_time = microtime(true);
}
public static function finish () { static::run(null); }
public static function results ($max_time = null) {
if (is_null($max_time))
$max_time = ini_get('max_execution_time');
$column = function ($values, $sizes = null, $separator = '|', $spacer = ' ', $pad_type = STR_PAD_BOTH) {
foreach ($values as $k => $value) {
$size = 20;
if(!is_null($sizes) && isset($sizes[$k]))
$size = $sizes[$k];
$values[$k] = str_pad (substr ($value, 0, $size), $size, $spacer, $pad_type);
}
return implode($separator, $values);
};
$columns = [25, 18, 15, 18];
$new_line = "\r\n";
echo $column (['', '| BENCHMARK |', '', ''], $columns, '+', '-') . $new_line;
echo $column (['Test Name', 'Total Time (s)', 'Iterations', 'Avg. Time (s)'], $columns) . $new_line;
$t_total = 0;
$a_total = 0;
foreach (static::$_times as $test => $marks) {
$total = 0;
if (empty($marks))
continue;
foreach($marks as $mark) { $total += $mark; }
$average = $total / count ($marks);
$t_total += $total;
$a_total += $average;
echo $column ([$test, number_format($total, 5), count ($marks), number_format($average, 5)], $columns) . $new_line;
}
$m_total = 100 * $t_total / $max_time;
echo $column (['', '', '', ''], $columns, '+', '-') . $new_line;
echo $column (['Total', number_format($t_total, 5), number_format($m_total, 3) . '%', number_format($a_total, 5)], $columns) . $new_line;
echo $column (['', '', '', ''], $columns, '+', '-') . $new_line;
}
public static function clean () {
static::$_times = [];
static::$_last_time = null;
static::$_last_name = null;
}
}
@rbngzlv

This comment has been minimized.

Copy link

rbngzlv commented Feb 25, 2018

Thanks, very useful!

@azazqadir

This comment has been minimized.

Copy link

azazqadir commented Mar 19, 2018

Why do you need a benchmark tool for Laravel when you can do performance benchmarks of Laravel using tools, like blitz.io or Apache Benchmarks. The process of using Apache Benchmarks for benchmarking Laravel performance is really easy.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.