Amir Sa
Amir Sa

Reputation: 251

How to estimate resource usage while a PHP code is running

I'm working on a project in PHP which is an improved model of an old PHP script. I claimed that new model will be more efficient in CPU and RAM usage. Now for evaluation, I want to estimate the ram & cpu usage during those processes. However the code is to small (a regular expression) but i believe in high load of input can show it self.

Is there any way to calculate an estimate or cpu & ram usage while the script is running?

Upvotes: 3

Views: 759

Answers (2)

hek2mgl
hek2mgl

Reputation: 157990

I would suggest to use the xdebug profiler. Using it you will know the resource usage even per function exactly and don't have to estimate it.

The extension will create so called cachegrind files which can be analyzed by graphical tools like KCachegrind or WinCachgrind

Btw if you want to get peak mem usage in php then add this at the last line:

echo sprintf("peak memory usage in bytes: %s\n", memory_get_peak_usage());

Upvotes: 2

Tom van der Woerdt
Tom van der Woerdt

Reputation: 29975

CPU usage: just time the code

$t_start = microtime(true);
useMyCode();
$t_end = microtime(true);

$total_time = $t_end - $t_start;

Memory usage: you can get a bit of an indication by using a "tick function":

$max_mem = 0;
register_tick_function(function() {
    global $max_mem;
    $cur_mem = memory_get_usage();
    if ($cur_mem > $max_mem) $max_mem = $cur_mem;
});

declare(ticks=1) {
    useMyCode();
}

echo $max_mem;

To best estimate the CPU usage, just run it 10000 times. That won't work for memory usage though.

Upvotes: 3

Related Questions