php getRusage()返回错误的信息?
-
02-10-2019 - |
题
我正在尝试确定我的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())
您的循环版本,我有以下时间:
用户:0.98、0.09、0.90系统:0.12、0.05、0.94
显然是差异。即使只是一个简单的 <? print_r(getrusage()) ?>
UTIME/静置距离为0至0.03。
尝试将循环运行更长的时间,并在其中做一些事情以增加CPU使用情况。现在,您的数字太小,无法准确测量。
其他提示
谢谢 马克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 ));
}
希望这对遇到同一问题的其他任何人都会有所帮助。
不隶属于 StackOverflow