In this tutorial we will create a basic php class with witch we will see in how much time a page loads
First we need to create the class that will handle the page load time. Bellow is the code we will need for the class:
Code:
<?php /** * A basic PHP Class to measure page load time * For support issues please refer to the webdigity forums : *www.webdigity.com * * ============================================================================== * * @version $Id: pageloadtime.class.php,v 1 2007/09/25 13:54:32 $ * @copyright Copyright (c) 2007 Nick Papanotas (http://www.webdigity.com) * @author Nick Papanotas <nikolas@webdigity.com> * @license http://opensource.org/licenses/gpl-license.php GNU General Public License (GPL) * * ============================================================================== */ class pageLoad{ var $start; var $end; function pageLoad(){ $this->start(); } function start(){ $this->start = $this->getTime(); } function end(){ $this->end = $this->getTime(); } function getLoadTime($format = '%01.2f'){ if (empty($this->end) )$this->end(); return sprintf($format, ($this->end - $this->start)); } function getTime(){ $time = microtime(); $time = explode(' ', $time); return $time[1] + $time[0]; } } ?>
The class has 5 functions. Bellow we will try to explain what each of them does:
pageLoad()
This is the constructor function. Whenever we initiate the class this function is executed and the class logs the time of the initiation.
start()
This is the actual function that logs the beginning time, thought we don't have to use it as the constructor does this.
end()
This is the same with the start() function, but it logs the time that our script ends. Again we don't have to use it as the next function we will describe is going to.
getLoadTime()
the getLoadTime() function will return the time passed from the beginning. You can give to the function a format string which will be used by sprintf() in order to format the time.
getTime()
This is a private function that returns the time at the time of call.
How to measure page load time with our class
Ok, enough with the theory, let's see how easy is to use this class:
Code:
<?php include 'pageloadtime.class.php';//This is the supposed file name where we added the class code $Load = new pageLoad;//Here is the point where we start counting /* Here is your code */ echo 'This page loaded in ' . $Load->getLoadTime() . ' seconds'; ?>
That's it, we are done. Hope you liked this tutorial :)