PHP计算页面执行时间函数

很多时候想要知道脚本效率时间,这时候就需要知道脚本的运行时间,然后去优化它。可能有些人看到了Discuz页面底部也会有一个“Processed in 0.030282 second(s)…”这样的提示,对,这就是脚本执行时间。

如何计算一段php程序代码的执行消耗时间?

对于系统时间,可能很多programmer对php的time()函数并不陌生,可惜time()函数只返回,自从 Unix 纪元(格林威治时间 1970 年 1 月 1 日 00:00:00)到当前时间的秒数。
没错,是秒.我们一段php程序代码执行耗时可能并不超过一秒,所以time()并不适用。

php提供了一个更为精确的时间函数microtime():

microtime — 返回当前 Unix 时间戳和微秒数。

格式: mixed microtime ([ bool $get_as_float ] )

函数以 “msec sec” 的格式返回一个字符串,sec 是自 Unix 纪元(0:00:00 January 1, 1970 GMT)起到现在的秒数,msec 是微秒部分。
如果输入参数为true,microtime() 将返回一个浮点数。

好了,然后的事情很简单,为了免于对返回的结果做复杂的字符串转换,我们设定microtime()输入参数为true,使得其返回的结果为浮点数。
然后在程序开始和结束分别计算一次,两次结果相减便是程序执行的时间。(PHP手册里有一句话:永远不要比较两个浮点数是否相等。 )
最后使用number_format格式化浮点数。此方法仅供测试,结果不一定精确。

Example #1 number_format() Example:

<?php
$number = 1234.56;

// english notation (default)
$english_format_number = number_format($number);
// 1,235

// French notation
$nombre_format_francais = number_format($number, 2, ',', ' ');
// 1 234,56

$number = 1234.5678;

// english notation without thousands separator
$english_format_number = number_format($number, 2, '.', '');
// 1234.57
?>

Example #1 用 microtime() 对脚本的运行计时

<?php
/**
 * Simple function to replicate PHP 5 behaviour
 */
function microtime_float() {
	list ( $usec, $sec ) = explode ( " ", microtime () );
	return (( float ) $usec + ( float ) $sec);
}

$time_start = microtime_float ();

// Sleep for a while
usleep ( 100 );

$time_end = microtime_float ();
$time = $time_end - $time_start;

echo "Did nothing in $time seconds\n";
?>

类:

<?
/**
 * 页面执行时间计算
 * @author hkshadow
 */
class RunTime//页面执行时间类
{
	private $starttime;//页面开始执行时间
	private $stoptime;//页面结束执行时间
	private $spendtime;//页面执行花费时间
	function getmicrotime()//获取返回当前微秒数的浮点数
	{
		list($usec,$sec)=explode(" ",microtime());
		return ((float)$usec + (float)$sec);
	}
	function start()//页面开始执行函数,返回开始页面执行的时间
	{
		$this->starttime=$this->getmicrotime();
	}
	function end()//显示页面执行的时间
	{
		$this->stoptime=$this->getmicrotime();
		$this->spendtime= $this->stoptime - $this->starttime;
	}
	function display()
	{
		$this->end();
		echo "<p>运行时间:".number_format($this->spendtime,10)."秒</p>";
	}
}

$timer=new Runtime();
$timer->start();  //执行脚本开始时间 
$timer->display(); //显示页面(脚本执行结束时间)
?>