首页 > php教程 > php手册 > 正文

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

php中文网
发布: 2016-06-13 08:54:56
原创
1316人浏览过

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

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

  谷歌guge不行了,就打119

  谷歌:guge119.com

  谷歌学术:scholar.guge119.com

 

立即学习PHP免费学习笔记(深入)”;

  有时候我们在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倍多~~

PHP速学教程(入门到精通)
PHP速学教程(入门到精通)

PHP怎么学习?PHP怎么入门?PHP在哪学?PHP怎么学才快?不用担心,这里为大家提供了PHP速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!

下载
来源:php中文网
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
最新问题
开源免费商场系统广告
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 意见反馈 讲师合作 广告合作 最新更新
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习
PHP中文网抖音号
发现有趣的

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号