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('Code snippet one');
tick('Code snippet two');

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 != ''){
    return $instance;

class ticks {
    private $tick = array();
    private static $instance;
    public static function inst(){
            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.

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

Leave a Reply

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

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

Google+ photo

You are commenting using your Google+ 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 )


Connecting to %s

%d bloggers like this: