[英]PHP getrusage() returning incorrect information?
我正在嘗試確定我的PHP腳本的CPU使用率。 我剛剛找到這篇文章 ,其中詳細介紹了如何查找系統和用戶CPU使用時間(第4節)。
但是,當我嘗試這些示例時,我收到了完全不同的結果。
第一個例子 :
sleep(3);
$data = getrusage();
echo "User time: ".
($data['ru_utime.tv_sec'] +
$data['ru_utime.tv_usec'] / 1000000);
echo "System time: ".
($data['ru_stime.tv_sec'] +
$data['ru_stime.tv_usec'] / 1000000);
結果是:
User time: 29.53
System time: 2.71
范例2 :
for($i=0;$i<10000000;$i++) {
}
// Same echo statements
結果:
User time: 16.69
System time: 2.1
例子3 :
$start = microtime(true);
while(microtime(true) - $start < 3) {
}
// Same echo statements
結果:
User time: 34.94
System time: 3.14
顯然,除了第三個示例中的系統時間,所有信息都不正確 。 那我在做什么錯? 我真的很希望能夠使用此信息,但它必須可靠。
我正在使用Ubuntu Server 8.04 LTS(32位),這是php -v
的輸出:
PHP 5.2.4-2ubuntu5.10 with Suhosin-Patch 0.9.6.2 (cli) (built: Jan 6 2010 22:01:14)
Copyright (c) 1997-2007 The PHP Group
Zend Engine v2.2.0, Copyright (c) 1998-2007 Zend Technologies
您可以使用系統的“時間”命令從外部驗證此信息:
/usr/bin/time php script.php
它將打印如下內容:
0.03user 0.00system 0:03.04elapsed 0%CPU (0avgtext+0avgdata 32752maxresident)k
0inputs+0outputs (0major+2234minor)pagefaults 0swaps
當然,不要忘記getrusage()信息是使用的CPU時間,而microtime()是掛鍾時間。 該程序可能會根據牆上的時鍾運行10分鍾,但在內部可能僅使用幾秒鍾的CPU時間。 然后,在系統上運行的所有后台程序,資源爭用以及常規內務處理中都爭奪CPU時間。
在如此短的時間內,要獲取准確的時間安排涉及太多因素。 在循環的while(microtime())
版本中運行了while(microtime())
,得到了以下計時信息:
用戶:0.98,0.09,0.90 sys:0.12,0.05,0.94
顯然,差異很大。 即使只是簡單的<? print_r(getrusage()) ?>
<? print_r(getrusage()) ?>
utime / stimes范圍為0到0.03。
嘗試長時間運行循環,並在其中進行一些操作以增加CPU使用率。 目前,您的數字太小,無法准確衡量。
多虧了Marc B的建議 ,我才能夠弄清楚可笑的短時間導致getrusage()
的計算出錯。
我創建了一個變通方法來丟棄這些不正確的數字。 這是代碼:
define('SCRIPT_START', microtime(1));
register_shutdown_function('record_activity');
/* Do work here */
function record_activity()
{
$data = getrusage();
$cpuu = ($data['ru_utime.tv_sec'] + $data['ru_utime.tv_usec'] / 1000000);
$cpus = ($data['ru_stime.tv_sec'] + $data['ru_stime.tv_usec'] / 1000000);
$renderedtime = round(microtime(1) - SCRIPT_START, 6);
// Have some log function to put this info somewhere
insert_record($renderedtime,
//Only pass user CPU time if it's less than or equal to rendered time
($renderedtime >= $cpuu ? $cpuu : NULL ),
//Only pass system CPU time if it's less than or equal to rendered time
($renderedtime >= $cpus ? $cpus : NULL ));
}
希望這將對遇到相同問題的其他人有所幫助。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.