首页  >  文章  >  php教程  >  php-timeit估计php函数的执行时间,php-timeitphp

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

WBOY
WBOY原创
2016-06-13 08:54:561183浏览

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

  首先,前段时间利用手头的日本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<span>) {
    if ($count <= 0<span>){
        echo "Error: count have to be more than zero"<span>;
        return -1<span>;
    }
    
    $nbargs = func_num_args<span>();
    if ($nbargs < 2<span>) {
        echo 'Error: No Funciton!'<span>;
        echo 'Usage:'<span>;
        echo "\ttimeit(count, 'function(param)')"<span>;
        echo "\te.g:timeit(100, 'function(0,2)')"<span>;
        return -1;                        // no function to time
<span>    }
    
    // Generate callback
    $func = func_get_arg(1<span>);
    $func_name = current(explode('(', $func<span>));
    if (!function_exists($func_name<span>)) {
        echo 'Error: Unknown Function'<span>;
        return -1;                    // can't test unknown function
<span>    }
    
    $str_cmd = ''<span>;
    $str_cmd .= '$start = microtime(true);'<span>;
    $str_cmd .= 'for($i=0; $i<'.$count.'; $i++) '.$func.';'<span>;
    $str_cmd .= '$end = microtime(true);'<span>;
    $str_cmd .= 'return ($end - $start);'<span>;
    
    return eval($str_cmd<span>);
}</span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span>

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

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


print timeit(1000, 'sqrt_nd(5)'<span>);
print "\n"<span>;
print timeit(1000, 'sqrt(5)');</span></span></span></span></span></span></span>

  测试结果如下:

0.028280019760132
0.0041000843048096

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

声明:
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn