Home >Backend Development >PHP Tutorial >Class code for calculating program running time in php
Copy the code The code is as follows:
class Timer {
private $StartTime = 0;//The time the program starts running
private $StopTime = 0;//The time the program ends
private $TimeSpent = 0;//The time it takes to run the program
function start(){//The program starts running
$this->StartTime = microtime();
}
function stop(){//The program ends
$this->StopTime = microtime();
}
function spent(){//The time it takes for the program to run
if ($this->TimeSpent) {
return $this->TimeSpent;
} else {
list($StartMicro, $StartSecond) = explode(" " , $this->StartTime);
list($StopMicro, $StopSecond) = explode(" ", $this->StopTime);
$start = doubleval($StartMicro) + $StartSecond;
$stop = doubleval ($StopMicro) + $StopSecond;
$this->TimeSpent = $stop - $start;
return substr($this->TimeSpent,0,8)."seconds";//Return the obtained program execution Time difference
}
}
}
$timer = new Timer();
$timer->start();
//...Code for program running
$timer->stop();
echo "program The running time is: ".$timer->spent();