php-timeit估计php函数的执行时间
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了php-timeit估计php函数的执行时间,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含1864字,纯文字阅读大概需要3分钟。
内容图文
![php-timeit估计php函数的执行时间](/upload/InfoBanner/zyjiaocheng/156/0d14546c6d6b4884a35aec9363224b95.jpg)
谷歌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倍多~~
以上就介绍了php-timeit估计php函数的执行时间,包括了方面的内容,希望对PHP教程有兴趣的朋友有所帮助。
内容总结
以上是互联网集市为您收集整理的php-timeit估计php函数的执行时间全部内容,希望文章能够帮你解决php-timeit估计php函数的执行时间所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。