Skip to content

Instantly share code, notes, and snippets.

@matsubo
Created August 19, 2013 05:56
Show Gist options
  • Save matsubo/6266079 to your computer and use it in GitHub Desktop.
Save matsubo/6266079 to your computer and use it in GitHub Desktop.
<?php
function benchmark(callable $block) {
$array = array();
for ($i = 0; $i < 10000; $i++) {
$array[] = mt_rand(1,1000000);
}
$start = microtime(true);
$block($array);
$end = microtime(true);
return $end - $start;
}
echo 'Count each time:' . benchmark(function($array) {
$try = 1000;
$j = 0;
while ($j < $try) {
for ($i = 1; $i < count($array); ++$i){}
$j++;
}
}) . PHP_EOL;
echo 'Count in variable:' . benchmark(function($array) {
$try = 1000;
$j = 0;
while ($j < $try) {
$count = count($array);
for ($i = 1; $i < $count; $i++){}
$j++;
}
}) . PHP_EOL;
@matsubo
Copy link
Author

matsubo commented Aug 19, 2013

PHP 5.4 on Debian 6.0 64bits.

% php count.php
Count each time:1.4978311061859
Count in variable:0.41650009155273

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment