PHP查看CPU的使用信息


PHP #cpu2014-04-15 22:39

要查看CPU的使用信息,我们用到 getrusage() 函数。该函数不适用于 Windows 平台。

print_r(getrusage());
/* prints
Array
(
    [ru_oublock] => 0
    [ru_inblock] => 0
    [ru_msgsnd] => 2
    [ru_msgrcv] => 3
    [ru_maxrss] => 12692
    [ru_ixrss] => 764
    [ru_idrss] => 3864
    [ru_minflt] => 94
    [ru_majflt] => 0
    [ru_nsignals] => 1
    [ru_nvcsw] => 67
    [ru_nivcsw] => 4
    [ru_nswap] => 0
    [ru_utime.tv_usec] => 0
    [ru_utime.tv_sec] => 0
    [ru_stime.tv_usec] => 6269
    [ru_stime.tv_sec] => 0
)
*/


这可能看起来有点神秘,除非你已经有系统管理员权限。以下是每个值的具体说明:

ru_oublock: block output operations
ru_inblock: block input operations
ru_msgsnd: messages sent
ru_msgrcv: messages received
ru_maxrss: maximum resident set size
ru_ixrss: integral shared memory size
ru_idrss: integral unshared data size
ru_minflt: page reclaims
ru_majflt: page faults
ru_nsignals: signals received
ru_nvcsw: voluntary context switches
ru_nivcsw: involuntary context switches
ru_nswap: swaps
ru_utime.tv_usec: user time used (microseconds)
ru_utime.tv_sec: user time used (seconds)
ru_stime.tv_usec: system time used (microseconds)
ru_stime.tv_sec: system time used (seconds)

要知道脚本消耗多少 CPU 功率,我们需要看看 ‘user time’ 和 ’system time’ 两个参数的值。秒和微秒部分默认是单独提供的。你可以除以 100 万微秒,并加上秒的参数值,得到一个十进制的总秒数。
例子:
 
// sleep for 3 seconds (non-busy)
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);
/* prints
User time: 0.011552
System time: 0
*/


尽管脚本运行用了大约 3 秒钟,CPU 使用率却非常非常低。因为在睡眠运行的过程中,该脚本实际上不消耗 CPU 资源。还有许多其他的任务,可能需要一段时间,但不占用类似等待磁盘操作等 CPU 时间。因此正如你所看到的,CPU 使用率和运行时间的实际长度并不总是相同的。
例子:
 
// loop 10 million times (busy) http://yige.org/
for($i=0;$i<10000000;$i++) {
}
$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);
/* prints
User time: 1.424592
System time: 0.004204
*/


这花了大约 1.4 秒的 CPU 时间,但几乎都是用户时间,因为没有系统调用。系统时间是指花费在执行程序的系统调用时的 CPU 开销。
例子:
 
$start = microtime(true);
// keep calling microtime for about 3 seconds
while(microtime(true) - $start < 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);
/* prints
User time: 1.088171
System time: 1.675315
*/

现在我们有相当多的系统时间占用。这是因为脚本多次调用 microtime() 函数,该函数需要向操作系统发出请求,以获取所需时间。你也可能会注意到运行时间加起来不到 3 秒。这是因为有可能在服务器上同时存在其他进程,并且脚本没有 100% 使用 CPU 的整个 3 秒持续时间。

相关文章

粤ICP备11097351号-1