<span class="hljs-meta"><?php
// Program section unrelated to the article
echo "Welcome to the PHP technical article.\n";
?>
<p><hr></p>
<p><h1>getrusage() Interpretation of Data Units Returned</h1></p>
<p><p>In PHP, the <code>getrusage<span>()
This code will output something similar to the following (with minor variations depending on the system):
</span>Array
(
[ru_utime.tv_sec] => 0
[ru_utime.tv_usec] => 123456
[ru_stime.tv_sec] => 0
[ru_stime.tv_usec] => 7890
[ru_maxrss] => 34560<span>
...
)
2. Field and Unit Explanations
- ru_utime.tv_sec / ru_utime.tv_usec
Represents user CPU time, in seconds and microseconds respectively. You can add these two values to get the precise total user CPU time.
- ru_stime.tv_sec / ru_stime.tv_usec
Represents kernel CPU time, also in seconds and microseconds.
- ru_maxrss
Represents the maximum resident set size used by the process. On Linux, this is in KB (kilobytes); on macOS, it is in bytes, so attention is needed here.
- ru_ixrss, ru_idrss, ru_isrss
These fields theoretically represent the memory usage of shared memory, unshared data memory, and unshared stack memory. However, they are typically unavailable on modern systems and return a value of 0.
- ru_minflt / ru_majflt
Number of page faults (page exceptions), measured in "occurrences," not time.
- ru_nswap
Number of times the process swapped, also in "occurrences."
- ru_inblock / ru_oublock
Number of block input/output operations (such as file system read/write operations), measured in "block operations," not bytes.
- ru_msgsnd / ru_msgrcv
Number of sent and received messages, in "occurrences."
- ru_nsignals
Number of signals received.
- ru_nvcsw / ru_nivcsw
Number of voluntary/involuntary context switches.
3. Example of Unit Conversion
Suppose we want to get the total user CPU time. We can write the following:
</span>$usage = getrusage();
$user_time = $usage["ru_utime.tv_sec"] + $usage["ru_utime.tv_usec"] / 1e6;
echo "User time: {$user_time}<span> seconds\n";
Similarly, you can perform the same operation on kernel time to obtain the total CPU time of the process.
4. Considerations
- The units returned may differ across operating systems, especially for the ru_maxrss field.
- Some fields may always return 0 on certain platforms due to system limitations in data collection.
- The getrusage() function does not provide real-time memory peak data and is more suited for performance analysis rather than resource limitation control.
Conclusion
The getrusage() function in PHP is an essential tool for understanding the resource consumption of your scripts. Understanding its returned values and units helps developers conduct more detailed performance tuning and monitoring.