php评论获取时间,获取脚本执行时间的php类

如何获取脚本执行时间?发现脚本的执行时间比预想的长很多,那么肯定是这段脚本编写有问题,需要进行代码优化。下面给大家介绍一个获取脚本执行时间的php类。

/*

@描述: Stopwatch这个类用户获取脚本执行时间

@作者: Klesti Hoxha

*/

class Stopwatch {

private $start;

private $end;

private $markup_start = array();

private $markup_end = array();

function __construct($markup=false) {

$this->start($markup);

}

public function start($markup=false) {

if (!$markup) {

$this->start = $this->getmicrotime();

} else {

$this->markup_start[$markup] = $this->getmicrotime();

}

}

public function stop($markup=false) {

if (!$markup) {

$this->end = $this->getmicrotime();

} else {

$this->markup_end[$markup] = $this->getmicrotime();

}

return $this->getDuration($markup);

}

public function getDuration($markup=false) {

if (!$markup) {

return number_format($this->end – $this->start,4);

} else {

return number_format($this->markup_end[$markup] – $this->markup_start[$markup],4);

}

}

public function reset($markup) {

if (!$markup) {

$this->start = 0;

$this->end = 0;

$this->markup_start = array();

$this->markup_end = array();

} else {

$this->markup_start[$markup] = 0;

$this->markup_end[$markup] = 0;

}

}

private function getmicrotime(){

list($usec, $sec) = explode(” “,microtime());

return ((float)$usec + (float)$sec);

}

}

?>

脚本很简单,就是简单的封装了一下,让我们可以方便的检测这个php文件的执行时间,以及其中的某段脚本的执行时间。

下面是使用这个脚本的例子:

start(“section1”);

for ($i = 0; $i < 10000; $i++) { //什么都不做! } $s->stop(“section1”);

//片段2

$s->start(“section2”);

for ($i = 0;$i < 20000; $i++) { // 什么都不做! } $s->stop(“section2”);

//片段3

$s->start(“section3”);

for ($i = 0;$i < 30000; $i++) { //什么都不做! } //片段3中的子片段 $s->start(“section3_nested”);

for ($i = 0;$i < 10000; $i++) { //什么都不做! } $s->stop(“section3_nested”);

$s->stop(“section3”);

//输出时间

echo “Section 1 Duration: ” . $s->getDuration(“section1″) . ” seconds. \n”;

echo “Section 2 Duration: ” . $s->getDuration(“section2″) . ” seconds. \n”;

echo “Section 3 Duration: ” . $s->getDuration(“section3″) . ” seconds. \n”;

echo “Section 3_nested (a subsection inside section 3): ” . $s->getDuration(“section3_nested”) . ” seconds. \n”;

?>

怎么样,很简单吧,一个好的脚本在设计到数据库操作时,当需要获取的数据量不大时,执行时间应该在0.3秒以内的,如果你的代码在执行的时候要几秒钟,很可能就是代码有问题,这个类就介绍到这里吧。

作者: 石巍

原载: 10V

版权所有,转载时必须以超链接形式注明作者和原始出处及本声明。



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值