Debug slow code with ticks

October 24, 2011

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;
        }
    }
}
Advertisements

A tip when you are stuck

June 20, 2011

The other day at work I was making this algorithm, but did not get it to work. It looked so simple, but it was not – so I worked with it for a few hours without result.

When I took the time of for a few days, and decided to look at the problem again I fixed it in a few minutes. It was not a perfect fix, but as good as.

So, the tip when you are stuck:

Take some days off, and think of other things, and when you are back you may se an easy solution.


Send large emails in php

March 17, 2011

I’ve encountered this problem once a long time ago, and used a lot of time finding a solution back then. Probably because no one really directly issued this problem.

When you send large text in your mail, specially HTML, you have to remember to encode the message right and chunk it. Why? The email standard RFC2822 only accepts line lengths of 998 chars, and if you send longer lines you probably encounter a lot of problems in different email clients. This may be line breaks or spaces after every chunk of 998 chars, that could be in the middle of an HTML tag or link, making the email body a mess.

To avoid this, you have to use base64 encoding on the email body header:

“Content-Transfer-Encoding: base64\r\n”

The second thing you have to do is to encode your content string with base64 and chunk it into chunks before appending to the email.

chunk_split(base64_encode($content))

base64 encoding is something email clients can read and because the sting of HTML is encoded into this format you don’t get the spaces between every chunk of content when the client displays the content.

These two lines is the only thing you probably need to append when you ha long text or large emails with data longer than 998 chars. Today I encountered this problem again, and I knew about the solution so I knew what to google to find the right answer. But I did not find it right away, because there was not any really good, and short, explanation anywhere that said exactly what I needed to do.


The blessing in documenting code

February 23, 2011

I’m currently working on this framework in PHP but I was very unsure about what features to add. That’s why I began to document in the code at once, but it didn’t work right. It was too many changes in the code to begin with and I didn’t really know what I wanted – so the documenting was a messy draft that had no effect and became soon outdated.

But, that’s not the whole story. A framework need a good API, and I began working with it and found that it was actually a lot of fun. Firstly I listed every method I could think of, and then I began to write the functionality of each of them including examples of their usage. This way I found a lot of things to improve on the method functionality, I got a really good flow on programming them. It resulted in a really great API documentation as well.

What did I learn?

Different projects need different types of documenting. If you are unsure about your project try a more planned approach and then when the project is finishing up – then write the documentation in code. Other projects that has a lot of repetition in how methods act(like getters and setters, or getall_xx_fromdatabase) – they are easy to document in the code as PHP Doc because you know how to implement them and what you need them for. There is no point in building an API for a site like that. It’s not about what works for you, it’s about what works for your project.

This approach works also on testing. There is no point it creating unit tests for a framework that is under developement and have no real structure in what methods return or work. If you have a project with a lot of methods where you have define what they do, you can easily write Unit Tests for these methods. But if you, as I have, a method that does a lot of different stuff – then the best way is to have a test page and test alongside documentation. Later on, when you do a change, you can check if the test page renders the right way. When you have finished you can polish this test page, and make UnitTest for every possible use case.

Learn how to be flexible in how to document. When you do it right it might be fun. But do document!


Database connection speed in php

September 2, 2010

So, on this current project of mine, I have one unfinished page that have currently 31 fast mysql queries(to a database that contain a very little data) – and I wanted to see how different settings would affect the speed. I have heard that connections are costly, but how costly are they really? These are the average results of my little test:

One connection for each query: 0,045 sec
One persistent connection for each query: 0,025 sec
One connection used in a Singleton pattern: 0,0175 sec
One persistent connection used in a Singleton pattern: 0,0165 sec

Summary:
The old method is the slowest by far! If you have many concurrent users on the webpage persistent connection will help a bit. But the best effect is from using a Singleton connection – or another method where you use one instance of the connection on all the queries. Persistent connection uses some time fetching the connection from mysql on the server, so it’s faster to do it in code.


Debug PHP: print_r() the array

April 2, 2010

I’ve used print_r method in PHP to print the contents of an array or object for a long time. I know there are some debugging tools out there, but I like it real simple, and print_r is really all I have needed.

Well, the mistake I’ve done is that I write this snippet all over my code:
echo '<pre>';
print_r($array);
echo '</pre>';

The work in removing all them or commenting out is something I sometimes forget. That is why I made a new kind of method to make it easier.
function preWrap($array){
echo '<pre>';
print_r($array);
echo '</pre>';
}

I don’t know if this is a really good way of doing it, but it helps. To do it so that removing the preWrap() call, or commenting it out, is not always needed, you can add this to it:

In top of index.php or config.php file:
$debug=true;//change to false to turn of debug mode

And then in the preWrap method add this:
if($debug){
echo '<pre>';
print_r($array);
echo '</pre>';
}

That’s my simple way of doing it.