我试图确定我的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显然,除了第三个例子中的系统时间之外,没有任何信息是正确的。那我做错什么了?我非常希望能够使用这些信息,但它必须是可靠的。
我使用的是UbuntuServer8.04LTS(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发布于 2010-04-28 18:53:35
您可以使用系统“time”命令在外部验证此信息:
/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())版本的三次运行时,我得到了以下时间:
用户: 0.98,0.09,0.90系统: 0.12,0.05,0.94
显然有很大的差异。即使是一个简单的<? print_r(getrusage()) ?>,也有从0到0.03的utime/utime。
尝试运行更长时间的循环,并在循环中做一些事情来增加cpu的使用。现在你的数字太小,无法精确测量。
发布于 2010-04-28 19:53:54
多亏了马克·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 ));
}希望这将对任何经历同样问题的人有所帮助。
https://stackoverflow.com/questions/2732024
复制相似问题