Measuring Resources used by PHP Script

Hi Experts,

Is there a way that I can find out how much resources a php script uses? I'm particularly interested in RAM and if possible CPU percentage.

Thank you
APD TorontoSoftware DeveloperAsked:
Who is Participating?

[Product update] Infrastructure Analysis Tool is now available with Business Accounts.Learn More

x
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

Zephyr ICTCloud ArchitectCommented:
If it's run under a process and it has a PID, you could use something like the following:

ps -p <pid> -o %cpu,%mem

Open in new window


Though, you should know that %cpu "is the CPU time used divided by the time the process has been running (cputime/realtime ratio), expressed as a percentage" according to the man for ps.
APD TorontoSoftware DeveloperAuthor Commented:
How do I know if I have a PID?

I thought that I can add a couple lines of code at the start and end of my script.
Zephyr ICTCloud ArchitectCommented:
Well. if you run "ps -ef" while the script is running you could check the list if something pops out ...
Probably not though ...

Another one to try is the command "top", which shows the performance of your server in total.

As for adjusting your script itself, maybe this will give you some ideas

I also found these interesting php tools interesting, though might not help you right now maybe.
- This one
- And this one
The 7 Worst Nightmares of a Sysadmin

Fear not! To defend your business’ IT systems we’re going to shine a light on the seven most sinister terrors that haunt sysadmins. That way you can be sure there’s nothing in your stack waiting to go bump in the night.

Ray PaseurCommented:
Some professionals like this:
http://www.xdebug.org/

PHP has some functions that may help with part of this question.
http://php.net/manual/en/function.memory-get-usage.php
http://php.net/manual/en/function.memory-get-peak-usage.php
http://php.net/manual/en/function.sys-getloadavg.php (never used this)

Untested, but maybe worth testing:
http://www.tonylea.com/2012/how-to-get-memory-and-cpu-usage-in-php/

I've used this class to time all or parts of a script.  It gives elapsed time, not CPU time.  Elapsed time incorporates the time spent waiting for external processes, database results, disk I/O, etc.
<?php // demo/class_Stopwatch.php

/**
 * A Class that allows us to see the elapsed time when running a script
 */
error_reporting(E_ALL);


// CREATE AN INSTANCE OF THE STOPWATCH
$t = new StopWatch;


// START THE TIMER
$t->start();

// DO SOME ACTIVITY THAT YOU WANT TO TIME
$x = file_get_contents('https://google.com/');

// GET A READOUT FROM THE TIMER
echo $t->readout();

// RESET THE TIMER
$t->reset();


// A SCRIPT TIMER FOR ALL OR PART OF A SCRIPT PHP 5+
// MAN PAGE http://php.net/manual/en/function.microtime.php
class StopWatch
{
    protected $a; // START TIME
    protected $s; // STATUS - IF RUNNING
    protected $z; // STOP TIME

    public function __construct()
    {
        $this->a = array();
        $this->s = array();
        $this->z = array();
    }

    // A METHOD TO PROVIDE A FINAL READOUT, IF NEEDED
    public function __destruct()
    {
        $ret = $this->readout();
        if (!$ret) return FALSE;
        echo
          __CLASS__
        . '::'
        . __FUNCTION__
        . '() '
        ;
        echo "<b>$ret</b>";
        echo PHP_EOL;
    }

    // A METHOD TO REMOVE A TIMER
    public function reset($name='TIMER')
    {
        // RESET ALL TIMERS
        if ($name == 'TIMER')
        {
            $this->__construct();
        }
        else
        {
            unset($this->a[$name]);
            unset($this->s[$name]);
            unset($this->z[$name]);
        }
    }

    // A METHOD TO CAPTURE THE START TIME
    public function start($name='TIMER')
    {
        $this->a[$name] = microtime(TRUE);
        $this->z[$name] = $this->a[$name];
        $this->s[$name] = 'RUNNING';
    }

    // A METHOD TO CAPTURE THE END TIME
    public function stop($name='TIMER')
    {
        $ret = NULL;

        // STOP ALL THE TIMERS
        if ($name == 'TIMER')
        {
            foreach ($this->a as $name => $start_time)
            {
                // IF THIS TIMER IS STILL RUNNING, STOP IT
                if ($this->s[$name])
                {
                    $this->s[$name] = FALSE;
                    $this->z[$name] = microtime(TRUE);
                }
            }
        }

        // STOP ONLY ONE OF THE TIMERS
        else
        {
            if ($this->s[$name])
            {
                $this->s[$name] = FALSE;
                $this->z[$name] = microtime(TRUE);
            }
            else
            {
                $ret .= "ERROR: CALL TO STOP() METHOD: '$name' IS NOT RUNNING";
            }
        }

        // RETURN AN ERROR MESSAGE, IF ANY
        return $ret;
    }

    // A METHOD TO READ OUT THE TIMER(S)
    public function readout($name='TIMER', $dec=3, $m=1000, $t = 'ms', $eol=PHP_EOL)
    {
        $str = NULL;

        // GET READOUTS FOR ALL THE TIMERS
        if ($name == 'TIMER')
        {
            foreach ($this->a as $name => $start_time)
            {
                $str .= $name;

                // IF THIS TIMER IS STILL RUNNING UPDATE THE END TIME
                if ($this->s[$name])
                {
                    $this->z[$name] = microtime(TRUE);
                    $str .= " RUNNING ";
                }
                else
                {
                    $str .= " STOPPED ";
                }

                // RETURN A DISPLAY STRING
                $lapse_time = $this->z[$name] - $start_time;
                $lapse_msec = $lapse_time * $m;
                $lapse_echo = number_format($lapse_msec, $dec);
                $str .= " $lapse_echo $t";
                $str .= $eol;
            }
            return $str;
        }

        // GET A READOUT FOR ONLY ONE TIMER
        else
        {
            $str .= $name;

            // IF THIS TIME IS STILL RUNNING, UPDATE THE END TIME
            if ($this->s[$name])
            {
                $this->z[$name] = microtime(TRUE);
                $str .= " RUNNING ";
            }
            else
            {
                $str .= " STOPPED ";
            }

            // RETURN A DISPLAY STRING
            $lapse_time = $this->z[$name] - $this->a[$name];
            $lapse_msec = $lapse_time * $m;
            $lapse_echo = number_format($lapse_msec, $dec);
            $str .= " $lapse_echo $t";
            $str .= $eol;
            return $str;
        }
    }
}

Open in new window

APD TorontoSoftware DeveloperAuthor Commented:
I added

echo '<br> MEMORY START ' . memory_get_usage(TRUE) . '<br>';
//...
echo '<br> MEMORY END ' . memory_get_usage(TRUE) . '<br>';

Open in new window


...At the start and end of my script in question, the output is as follows.


MEMORY START 10,485,760

MEMORY END 55,312,384

Of course I added the commas, but what does this mean?

As well, I know that in a Windows environment if you run out of RAM, it uses your harddrive to compensate, and slows it down. It is true in Linux as well?

spravtek - are those Windows commands?
Zephyr ICTCloud ArchitectCommented:
MEMORY START 10,485,760

MEMORY END 55,312,384

Of course I added the commas, but what does this mean?

Maybe it's bytes? Would mean that it started with 10mb and finished at 55mb...

spravtek - are those Windows commands?
Which commands are you referring to?
APD TorontoSoftware DeveloperAuthor Commented:
So my script uses 45mb?

I'm referring to top and sp-sf

Is my assumption correct re if I run out ram...
Zephyr ICTCloud ArchitectCommented:
top and ps -ef are linux commands ...

Is my assumption correct re if I run out ram...

Linux has what is called a swap partition that will be used to swap out lesser used pages to disk, so it's kinda the same as with Windows yes.
Dave BaldwinFixer of ProblemsCommented:
You might also want to take a look at 'memory_get_peak_usage'.  http://php.net/manual/en/function.memory-get-peak-usage.php
APD TorontoSoftware DeveloperAuthor Commented:
What is the difference between memory_get_peak_usage and memory_get_usage?

Does the above means my script needs 45MB to run?

FYI, I am updating an Excel file with many sheets and color, so the high memory is not surprising, I just want to make sure I have enough memory on the server.
Dave BaldwinFixer of ProblemsCommented:
No your script needs 55MB to run including the PHP interpreter which is the initial 10MB.  But PHP will release memory when it is done with it in some circumstances.  Checking memory usage at the beginning and end won't catch any extra memory used and released in between.  That's why I suggested 'memory_get_peak_usage'.
APD TorontoSoftware DeveloperAuthor Commented:
Now, with peak usage I get

MEMORY START 10485760

MEMORY END 60293120

So, my script uses 50mb + 10mb for the interpreter, correct?

Under phpInfo() is this defined by memory_limit and 0 (zero) means not to pose limits on PHP scripts?
Dave BaldwinFixer of ProblemsCommented:
So, my script uses 50mb + 10mb for the interpreter, correct?
That's what it looks like.

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
PHP

From novice to tech pro — start learning today.