jump to navigation

PHP Optimization – Using A Timer To Benchmark Code And Increase Speed October 17, 2010

Posted by Tournas Dimitrios in PHP.
trackback

Well there’s seemingly always a better way to do things. A simple code tweak can drastically improve the execution time of your web application. The faster your application executes the quicker you release precious server resources.

The first step in optimizing your existing PHP-based web application for speed is knowing which portions of your website need to be improved. Do your MySQL queries take too long? Are you using efficient functions? Are you using unnecessary server resources? In my web applications I use a timer class to benchmark how long queries, functions, and entire pages are taking to complete.

class timer
{
    var $start;
    var $pause_time;

    /*  start the timer  */
    function timer($start = 0)
    {
        if($start) { $this->start(); }
    }

    /*  start the timer  */
    function start()
    {
        $this->start = $this->get_time();
        $this->pause_time = 0;
    }

    /*  pause the timer  */
    function pause()
    {
        $this->pause_time = $this->get_time();
    }

    /*  unpause the timer  */
    function unpause()
    {
        $this->start += ($this->get_time() - $this->pause_time);
        $this->pause_time = 0;
    }

    /*  get the current timer value  */
    function get($decimals = 8  )
    {
        return round(($this->get_time() - $this->start),$decimals);
    }

    /*  format the time in seconds  */
    function get_time()
    {
        list($usec,$sec) = explode(' ', microtime());
        return ((float)$usec + (float)$sec);
    }
}

The usage :

.
$timer = new timer(1); // constructor starts the timer, so no need to do it ourselves 
/*
..............mysql query ......................
*/
$query_time = $timer->get();
/*
....page procecing
.
.
.
*/
$processing_time = $timer->get();

Once you know which areas of your website need improvement, making your code more efficient can be easy if you’re code is well-commented and organized. Use the timer&mdashwhich areas of your website did you notice needed improvement and how did you optimize the code? I’d love to hear your problems and solutions!

Comments»

No comments yet — be the first.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s