bench_loop.php


start();
$target_function = array(
    'bench_array_sum',
    'bench_for_loop',
    'bench_for_precount',
    'bench_while_loop',
    'bench_while_precount',
    'bench_while_currentshift',
    'bench_while_shift',
    'bench_while_next',
    'bench_foreach_loop',
    'bench_whileeach'
);
$target_sum = 0;
$target_array = array();
for($i = 0; $i < 4000; $i++) {
    $data = rand(1,10);
    $target_array[] = $data;
    $target_sum += $data;
}
$timer->setMarker('make_data');
foreach ($target_function as $function) {
    $result = $function($target_array);
    if ($result != $target_sum) {
        exit($function . " return invalid valuen");
    }
    $timer->setMarker($function);
}
$timer->stop();
$timer->display();
function bench_array_sum($target_array)
{
    return array_sum($target_array);
}
function bench_for_loop($target_array)
{
    $sum = 0;
    for ($i = 0; $i < count($target_array); $i++) {
        $sum += $target_array[$i];
    }
    return $sum;
}
function bench_for_precount($target_array)
{
    $sum = 0;
    $target_array_count = count($target_array);
    for ($i = 0; $i < $target_array_count; $i++) {
        $sum += $target_array[$i];
    }
    return $sum;
}
function bench_while_loop($target_array)
{
    $i = 0;
    $sum = 0;
    while ($i < count($target_array)) {
        $sum += $target_array[$i];
        $i++;
    }
    return $sum;
}
function bench_while_precount($target_array)
{
    $i = 0;
    $sum = 0;
    $target_array_count = count($target_array);
    while ($i < $target_array_count) {
        $sum += $target_array[$i];
        $i++;
    }
    return $sum;
}
function bench_while_shift($target_array)
{
    $sum = 0;
    while (NULL !== ($value = array_shift($target_array))) {
        $sum += $value;
    }
    return $sum;
}
function bench_while_currentshift($target_array)
{
    $sum = 0;
    while (current($target_array) !== false) {
        $sum += array_shift($target_array);
    }
    return $sum;
}
function bench_while_next($target_array)
{
    $sum = 0;
    $sum+= current($target_array);
    while (($value = next($target_array)) !== false) {
        $sum += $value;
    }
    return $sum;
}
function bench_foreach_loop($target_array)
{
    $sum = 0;
    foreach ($target_array as $value) {
        $sum += $value;
    }
    return $sum;
}
function bench_whileeach($target_array)
{
    $sum = 0;
    while (list($key, $value) = each($target_array)) {
        $sum += $value;
    }
    return $sum;
}
?>

投稿者: halt

PHPプログラマ。

コメントを残す

メールアドレスが公開されることはありません。 * が付いている欄は必須項目です

ねこ認証:9つのパネルの中からねこを3匹選んでください