·您现在的位置: 云翼网络 >> 文章中心 >> 网站建设 >> 网站建设开发 >> php网站开发 >> php-timeit估计php函数的执行时间

php-timeit估计php函数的执行时间

作者:佚名      php网站开发编辑:admin      更新时间:2022-07-23

  首先,前段时间利用手头的日本VPS搭建了一个google代理,访问速度还行,分享给大家:

  谷歌guge不行了,就打119

  谷歌:guge119.com

  谷歌学术:scholar.guge119.com

 

  有时候我们在php性能优化的时候,需要知道某个函数的执行时间,在Python中,有timeit模块,在PHP中不知道有没有类似的模块?

  于是,我自己写了一个简单的timeit函数,如下:

/**
 * Compute the delay to execute a function a number of time
 * @param $count    Number of time that the tests will execute the given function
 * @param $function        the function to test. Can be a string with parameters (ex: 'myfunc(123, 0, 342)') or a callback
 * @return float            Duration in seconds (as a float)
 */
function timeit($count, $function) {
    if ($count <= 0){
        echo "Error: count have to be more than zero";
        return -1;
    }
    
    $nbargs = func_num_args();
    if ($nbargs < 2) {
        echo 'Error: No Funciton!';
        echo 'Usage:';
        echo "\ttimeit(count, 'function(param)')";
        echo "\te.g:timeit(100, 'function(0,2)')";
        return -1;                        // no function to time
    }
    
    // Generate callback
    $func = func_get_arg(1);
    $func_name = current(explode('(', $func));
    if (!function_exists($func_name)) {
        echo 'Error: Unknown Function';
        return -1;                    // can't test unknown function
    }
    
    $str_cmd = '';
    $str_cmd .= '$start = microtime(true);';
    $str_cmd .= 'for($i=0; $i<'.$count.'; $i++) '.$func.';';
    $str_cmd .= '$end = microtime(true);';
    $str_cmd .= 'return ($end - $start);';
    
    return eval($str_cmd);
}

  测试一下自己写的一个求根算法与系统内置求根函数的执行时间,如下:

//取平方根
function sqrt_nd($num){
    $value = $num;
    while(abs($value*$value -$num) > 0.001){
        $value = ($value + $num/$value)/2;
    }
    return $value;
}


PRint timeit(1000, 'sqrt_nd(5)');
print "\n";
print timeit(1000, 'sqrt(5)');

  测试结果如下:

0.028280019760132
0.0041000843048096

  可见,内置求根函数比自定义的求根函数快了6倍多~~