如何计算我的 php 脚本实际使用的 CPU 时间?
注意这不是我要找的:
<?php
$begin_time=microtime(true);
//..
//end of the script:
$total_time=microtime(true)-$begin_time;
因为那会给我流逝的时间。这可能包括同时运行的不相关进程所使用的大量时间,以及等待 i/o 所花费的时间。
我看到有 getrusage(),但文档页面中的用户评论说:
getrusage() reports kernel counters that are updated only once application loses context and a switch to kernel space happens. For example on modern Linux server kernels that would mean that getrusage() calls would return information rounded at 10ms, desktop kernels - at 1ms.
getrusage() isn't usable for micro-measurements at all - and getmicrotime(true) might be much more valuable resource.
所以这似乎不是一个选择,是吗?
我有什么选择?
最佳答案
定义“您的”I/O。从技术上讲,内存到 cpu 寄存器的移动是 I/O。你是说你想从你的计算中删除那个时间? (我猜不是)
我的意思是您最有可能希望以某种方式分析您的代码。如果您想测量未花在读取/写入文件或网络套接字上的时间,只需使用 microtime 并在执行 I/O 的部分周围放置额外的调用。然后您还将了解您的 I/O 占用了多少时间。您更有可能会发现某些循环花费的时间比您预期的要多。
当我像这样进行概要分析时,我要么使用 eclipse 中的概要分析工具,要么使用时间记录器并将时间记录到代码中的某种二进制搜索式插入。通常我会找到一些占用 85% 测量时间的小代码区域,然后在那里进行优化。
另请注意,不要让完美成为实用的敌人。在您的流程中,90% 的时间您的调用不会被其他流程打断,您的微时间计数将足够接近。
关于php - 如何获得 PHP 中使用的实际 CPU 时间?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16023067/