• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

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

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

  首先,前段时间利用手头的日本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倍多~~


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
php自动生成不重复的id发布时间:2022-07-10
下一篇:
phpSESSION不能跨页面传递发布时间:2022-07-10
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap