4

如何计算我的 php 脚本实际使用的 CPU 时间?

请注意,这不是我要找的:

<?php
$begin_time=microtime(true);
//..
//end of the script:
$total_time=microtime(true)-$begin_time;

因为那会给我过去的时间。这可能包括同时运行的不相关进程使用的大量时间,以及等待 i/o 所花费的时间。

我已经看到有 getrusage(),但是文档页面中的用户评论说:

getrusage() 报告内核计数器,这些计数器仅在应用程序丢失上下文并且发生切换到内核空间时才更新。例如,在现代 Linux 服务器内核上,这意味着 getrusage() 调用将在 10 毫秒内返回四舍五入的信息,桌面内核 - 在 1 毫秒内。

getrusage() 根本不能用于微测量 - 而 getmicrotime(true) 可能是更有价值的资源。

所以这似乎不是一个选择,是吗?

我有什么选择?

4

2 回答 2

1

Define "your" I/O. Technically a move of memory to cpu registers is I/O. Are you saying you want to remove that time from your calculation? (I'm guessing no)

What I'm getting at is you are looking to profile your code in some way most likely. If you want to measure time not spent reading/writing to files or network sockets, just use microtime and put extra calls around portions doing I/O. Then you will also get an idea of how much time your I/O is taking. More likely you will find you have some loop taking more time than you expect.

When I profile like this I either use profiling tools in eclipse, or I use a time logger and do some kind of binary search-ish insertion of the time logging into the code. Usually I find some small area of code that is taking 85% of the measured time and do optimization there.

Also as a side note, don't let the perfect become the enemy of the practical. 90% of the time during your process your calls won't be interrupted by some other process and your microtime counts will be close enough.

于 2013-04-15T19:29:00.747 回答
0

您可以使用getrusage()

完整示例:

<?php

function rutime($ru, $rus, $index){
    return ($ru["ru_$index.tv_sec"]*1000 + intval($ru["ru_$index.tv_usec"]/1000))
     -  ($rus["ru_$index.tv_sec"]*1000 + intval($rus["ru_$index.tv_usec"]/1000));
}

$cpu_before = getrusage();
$ms = microtime(true) * 1000;

sleep(3);
$tab = [];
for($i = 0; $i < 500000; $i++) {
  $tab[] = $i;
}

$cpu_after = getrusage();
echo "Took ".rutime($cpu_after, $cpu_before, "utime")." ms CPU usage" . PHP_EOL;
echo "Took ".((microtime(true) * 1000) - $ms)." ms total". PHP_EOL;

来源:https ://helpdesk.nodehost.ca/en/article/how-to-calculate-real-cpu-usage-in-a-php-script-o3ceu8/

于 2020-05-12T18:43:14.577 回答