The execution time is perhaps one of the most crucial element to your scripts. Very few individuals are going to want to wait around while your PHP script performs several server-intensive actions. The more server-intensive you make it, the more the user has to wait for those actions to complete before displaying the HTML.
Although this isn't an article on how to make your scripts more efficient. It is an article on how you can monitor the execution time and identify bottlenecks!
The execution time can be determined by calculating the microtime at the beginning and at the end of your PHP script. I am using TalkPHP's timer class as the example here - this can be downloaded for free, see the link at the end of the article.
PHP Code:
public function start()
{
$iMicrotime = microtime();
$iMicrotime = explode(' ', $iMicrotime);
$this->m_iStartTime = $iMicrotime[1] + $iMicrotime[0];
}
The start function calculates the microtime. Now, microtime creates 2 blocks of numbers which we reverse and assign to our member variable.
PHP Code:
public function stop()
{
$iMicrotime = microtime();
$iMicrotime = explode(' ', $iMicrotime);
$this->m_iEndTime = $iMicrotime[1] + $iMicrotime[0];
}
The stop function is almost identical in its approach and simply assigns the returned data from the microtime function to a different member variable.
Once we have the 2 times stored in member variables, we can calculate how long the execution time took. Keep in mind that the start function would be called at the beginning and then stop at the very end. Our display function will then deduct 1 from the other to calculate the execution time.
PHP Code:
$iTotalTime = $this->m_iEndTime - $this->m_iStartTime;
We deduct the start time from the end time. The variable the result was assigned to will now contain our execution time. Bear in mind that this method, using microtime, is extremely precise.
Once we have done that we can echo out our results. The result would be something like the following:
Quote:
|
Script execution took a total time of 0.000140190124512 seconds
|
Download: If you wish to download the simple yet efficacious execution time script to use in your projects,
you may download it here.