Skip to content

Instantly share code, notes, and snippets.

@matpratta
Created January 13, 2017 13:05
Show Gist options
  • Select an option

  • Save matpratta/cb5a040edb84f306e157739f07dec4cd to your computer and use it in GitHub Desktop.

Select an option

Save matpratta/cb5a040edb84f306e157739f07dec4cd to your computer and use it in GitHub Desktop.
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

rbngzlv commented Feb 25, 2018

Copy link
Copy Markdown

Thanks, very useful!

@azazqadir

Copy link
Copy Markdown

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