您的位置:首页 > 编程语言 > PHP开发

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

2015-09-05 16:00 525 查看
  首先,前段时间利用手头的日本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倍多~~
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: