首先,前段時間利用手邊的日本VPS搭建了一個google代理,訪問速度還行,分享給大家:
谷歌guge不行了,就打119谷歌學術: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>
可見,內建求根函數比自訂的求根函數快了6倍多~~
以上就介紹了php-timeit估計php函數的執行時間,包含了面向的內容,希望對PHP教學有興趣的朋友有幫助。