国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 開發 > PHP > 正文

使用php-timeit估計php函數的執行時間

2024-05-04 23:38:58
字體:
來源:轉載
供稿:網友

當我們在使用php性能優化的時候,需要知道某個函數的執行時間,在python中,我們有timeit模塊給我們實現,在php有沒有類似的模塊?接下來,小編給大家分享我寫的一個簡單timeit函數,需要的朋友可以參考下

廢話不多說了,直接把我寫的timeit函數分享給大家,具體內容如下:

 

 
  1. /** 
  2. * Compute the delay to execute a function a number of time 
  3. * @param $count Number of time that the tests will execute the given function 
  4. * @param $function the function to test. Can be a string with parameters (ex: 'myfunc(123, 0, 342)') or a callback 
  5. * @return float Duration in seconds (as a float) 
  6. */ 
  7. function timeit($count, $function) { 
  8. if ($count <= 0){ 
  9. echo "Error: count have to be more than zero"
  10. return -1; 
  11. $nbargs = func_num_args(); 
  12. if ($nbargs < 2) { 
  13. echo 'Error: No Funciton!'
  14. echo 'Usage:'
  15. echo "/ttimeit(count, 'function(param)')"
  16. echo "/te.g:timeit(100, 'function(0,2)')"
  17. return -1; // no function to time 
  18. // Generate callback 
  19. $func = func_get_arg(1); 
  20. $func_name = current(explode('(', $func)); 
  21. if (!function_exists($func_name)) { 
  22. echo 'Error: Unknown Function'
  23. return -1; // can't test unknown function 
  24. $str_cmd = ''
  25. $str_cmd .= '$start = microtime(true);'
  26. $str_cmd .= 'for($i=0; $i<'.$count.'; $i++) '.$func.';'
  27. $str_cmd .= '$end = microtime(true);'
  28. $str_cmd .= 'return ($end - $start);'
  29. return eval($str_cmd); 

測試一下自己寫的一個求根算法與系統內置求根函數的執行時間,如下:

 

 
  1. //取平方根 
  2. function sqrt_nd($num){ 
  3. $value = $num; 
  4. while(abs($value*$value -$num) > 0.001){ 
  5. $value = ($value + $num/$value)/2; 
  6. return $value; 
  7. print timeit(1000, 'sqrt_nd(5)'); 
  8. print "/n"
  9. print timeit(1000, 'sqrt(5)'); 

測試結果如下:

0.028280019760132

0.0041000843048096

可見,內置求根函數比自定義的求根函數快了6倍多~~

php中檢測函數執行時間的功能使用的方法

PHP 中的 microtime() 函數可以實現

microtime() 函數返回當前 Unix 時間戳和微秒數。

microtime(get_as_float)

參數說明

get_as_float 如果給出了 get_as_float 參數并且其值等價于 TRUE,該函數將返回一個浮點數。

本函數僅在支持 gettimeofday() 系統調用的操作系統下可用。

例如:

 

 
  1. <?php 
  2. $start_time = microtime(true); 
  3. for($i=1;$i<=1000;$i++){ 
  4. echo $i.'<br>'
  5. $end_time = microtime(true); 

echo '循環執行時間為:'.($end_time-$start_time).' s';

?>

發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 上杭县| 开远市| 高密市| 满城县| 涿州市| 正阳县| 长沙县| 明水县| 永和县| 万年县| 稻城县| 冕宁县| 阿图什市| 全州县| 山阳县| 防城港市| 甘德县| 潼南县| 宣汉县| 田东县| 广昌县| 香港| 萨嘎县| 德州市| 株洲县| 瑞安市| 新丰县| 香港| 普格县| 视频| 阿城市| 金寨县| 伊金霍洛旗| 雅安市| 南江县| 敖汉旗| 开江县| 永平县| 文昌市| 巨鹿县| 葫芦岛市|