Skip to content

Instantly share code, notes, and snippets.

@shin1x1
Created August 23, 2016 01:16
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save shin1x1/99b3ca3f8ba5799e29537b6ce4b37e65 to your computer and use it in GitHub Desktop.
Save shin1x1/99b3ca3f8ba5799e29537b6ce4b37e65 to your computer and use it in GitHub Desktop.
<?php
function benchmark($title, $loop = 1, callable $target)
{
echo '# ' . $title, PHP_EOL;
$start = microtime(true);
for ($i = 0; $i < $loop; $i++) {
$target();
}
echo (microtime(true) - $start) / $loop, PHP_EOL;
echo PHP_EOL;
}
function benchmark_loop($title, callable $target)
{
foreach ([20, 200, 2000, 20000, 200000] as $no) {
$string = str_repeat(' ', $no) . 'a';
benchmark($title . ' - ' . $no, 3, function () use ($string, $target) {
return $target($string);
});
}
}
benchmark_loop('\s+$', function ($string) {
return preg_replace('/\s+$/', '', $string);
});
benchmark_loop('\s++$', function ($string) {
return preg_replace('/\s++$/', '', $string);
});
benchmark_loop('rtrim', function ($string) {
return rtrim($string);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment