views:

91

answers:

1

In PHP, is there a way I can capture what the CPU usage is of each ImagaMagick/GraphicsMagick method I execute? Memory usage would be nice, too.

Basically, I'm trying to benchmark how much resources each library uses in my application.

Failed attempt:

exec('convert a.jpg a.png');

$result = array();

// Loop until process is detected
do
{
    exec('ps -eo comm,%cpu,%mem | grep ' . "convert", $result);
}
while($result === array());

// Display the changing CPU and memory usage of the process
do
{
    print_r($result);
    exec('ps -eo comm,%cpu,%mem | grep ' . "convert", $result);
}
while($result !== array());
+1  A: 

Memory usage should be a matter of recording the output of memory_get_usage(true) and memory_get_peak_usage(true) before and after each call you want to measure, then subtracting them.

CPU usage I'm not sure about. On unix systems it could involve doing exec() to get the output of ps -ef | grep $phpPid, then parsing that. You can get $phpPid = getmypid();

Fanis
How do I get the PID of the convert process (the library I call from PHP via exec())? That's the CPU usage I am interested in, I think.
StackOverflowNewbie
If it's the php process itself, then `getmypid()` will give you its process id. If it's a separate library, find its binary executable name and `grep` for that: `ps -ef | grep $binaryName`.
Fanis
@Fanis, ps -ef wasn't giving me what I needed, but ps -eo comm,%cpu,%mem was. Attempting to follow your suggestion, I've created a script that still doesn't work for me. My original post has been edited to show you what I did. Do you see what I am doing wrong?
StackOverflowNewbie
Ok now I see what you mean. `exec()` will wait until convert has completed, so you won't see that process in `ps` afterwards. A possible solution in this case would be to have your script A launch a separate script B right before the `exec()`. Script B can do the checking of `ps` like you're doing, and report to some shared space (eg a file) the results.
Fanis