Detailed explanation of how to check memory and CPU usage in php

伊谢尔伦
Release: 2023-03-12 06:02:01
Original
4987 people have browsed it

1. View memory usage

Observing the memory usage of your program allows you to better optimize your code.
PHP has a garbage collection mechanism and a very complex memory management mechanism. You can find out how much memory your script is using. To know the current memory usage, you can use the ?memory_get_usage() function, if you want to know the peak memory usage, you can call the memory_get_peak_usage() function .

echo "Initial: ".memory_get_usage()." bytes \n";
/* 输出
Initial: 361400 bytes
*/
// 使用内存
for ($i = 0; $i < 100000; $i++) {
$array []= md5($i);
}
// 删除一半的内存
for ($i = 0; $i < 100000; $i++) {
unset($array[$i]);
}
echo "Final: ".memory_get_usage()." bytes \n";
/* prints
Final: 885912 bytes
*/
echo "Peak: ".memory_get_peak_usage()." bytes \n";
/* 输出峰值
Peak: 13687072 bytes
*/
Copy after login

2. Check the CPU usage
Use the ?getrusage() function to let you know the CPU usage. Note that this feature is not available under Windows.

print_r(getrusage());
/* 输出
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
)
*/
Copy after login

This structure seems very obscure, unless you know the CPU very well. Here are some explanations:

ru_oublock: block output operation
ru_inblock: block input operation
ru_msgsnd: sent message
ru_msgrcv: received message
ru_maxrss: maximum resident Retention set size
ru_ixrss: Total shared memory size
ru_idrss: Total non-shared memory size
ru_minflt: Page recycling
ru_majflt: Page invalidation
ru_nsignals: Received signals
ru_nvcsw: Active context switching
ru_nivcsw: Passive context switching
ru_nswap: Swap area
ru_utime.tv_usec: User mode time (microseconds)
ru_utime.tv_sec: User mode time (seconds)
ru_stime.tv_usec : System kernel time (microseconds)
ru_stime.tv_sec: System kernel time?(seconds)

The above is the detailed content of Detailed explanation of how to check memory and CPU usage in php. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template