Debug slow code with ticks

I made this small snippet of code today, using my style of coding with a singleton class wrapped into a function. The idea is to time the differents parts of the code to find where the code is slowest, and thus, where to improve and optimize. The way you use the code is like this:

tick('Initialize');
/* CODE TO TEST */
tick('Code snippet one');
/* CODE TO TEST */
tick('Code snippet two');
tick()->show();

This will echo something like:

Msg: Initialize
Msg: Code snippet one
Time: 3.543 sec
Msg: Code snippet two
Time: 1.002 sec

Here is the full code:

function tick($msg = ''){
    $instance = ticks::inst();
    if($msg != ''){
        $instance->tick($msg);
    }
    return $instance;
}

class ticks {
    private $tick = array();
    private static $instance;
   
    public static function inst(){
        if(!isset(self::$instance)){
            self::$instance = new self();
        }
        return self::$instance;
    }
   
    public function tick($msg=''){
        $time = (string)microtime(true);
        $this->tick[$time] = $msg;
    }
   
    public function show(){
        $last = 0;
        foreach($this->tick as $time => $msg){
            $time = (float)$time;
            echo 'Msg: "'.$msg.'"';
            if($last_time != 0){
                $sec = round($time-$last, 3);
                echo 'Time: "'.$sec.' sec"';
            }
            $last = $time;
        }
    }
}

2 Responses to Debug slow code with ticks

  1. I’d also check out XHProf/XHGUI, if you’re able to install PHP extensions.

    http://phpadvent.org/2010/profiling-with-xhgui-by-paul-reinheimer

  2. […] Debug slow code with ticks « IndividualWeb […]

Leave a comment