<?php
//==========================================================================//
// The Class
//**************************************************************************//
class ExecutionTime
{
// Class Constructor
function ExecutionTime()
{
// Initialize variables
$this->ExecutionStart();
$this->ExecutionEnd();
$this->Msg = "Execution took <b>%f</b> seconds to complete.";
}
// This Function is to be called before the start of Execution
function ExecutionStart()
{
$this->StartTime = $this->GetMicroTime();
}
// This Function is to be called at the End of Execution
function ExecutionEnd()
{
$this->EndTime = $this->GetMicroTime();
}
// This Function returns the time taken for the code execution
function GetExecutionTime()
{
return $this->EndTime - $this->StartTime;
}
function PrintTime($Msg = 0)
{
$Msg = !$Msg ? $this->Msg : $Msg;
// If the Start and End times are the same take the End time as current time
if($this->EndTime == $this->StartTime)
{
$this->EndTime = $this->GetMicroTime();
}
printf($Msg, $this->GetExecutionTime());
}
// This function helps in returning the result as float
// even in PHP 4
function GetMicroTime()
{
list($MicroSec, $Sec) = explode(" ", microtime());
return ((float)$MicroSec + (float)$Sec);
}
}
?>
Example Usage
<?php
include_once ("ExecutionTime.class.php");
$ET = new ExecutionTime;
$ET->ExecutionStart();
// Execute Code Here
sleep(2);
// Code Execution Ends
$ET->ExecutionEnd();
echo "The code execution started at " . date('g:i:s A', $ET->StartTime) . " and ended at ". date('g:i:s A', $ET->EndTime)."<br />";
$ET->PrintTime();
?>