温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

PHP如何实现记录代码运行时间封装类

发布时间:2021-06-22 15:24:31 来源:亿速云 阅读:144 作者:小新 栏目:web开发

这篇文章给大家分享的是有关PHP如何实现记录代码运行时间封装类的内容。小编觉得挺实用的,因此分享给大家做个参考,一起跟随小编过来看看吧。

示例代码

class TimeCost
{

 private $cost = array();
 private $record = array();
 private $scale = 6;
 public function __construct($scale = 6)
 {
 $this->cost = array();
 $this->record = array();
 $this->scale = $scale;
 }

 public function __toString()
 {
 return $this->getString();
 }

 /**
 * start to cal time.
 *
 * @param mixed $key
 */
 public function addCost($key)
 {
 $this->cost[$key] = microtime(true);
 }

 /**
 * stop to cal time.
 *
 * @param mixed $key
 */
 public function closeCost($key)
 {
 $cost = bcsub(microtime(true), $this->cost[$key], $this->scale);

 if (in_array($key, array_keys($this->record))) {
  $this->record[$key] = bcadd($cost, $this->record[$key], $this->scale);
 } else {
  $this->record[$key] = $cost;
 }
 return $cost;
 }

 
 public function getString($key = null)
 {
 if ($key) {
  return "{$key}[{$this->record[$key]}]";
 }

 $str = '';
 foreach ($this->record as $k => $v) {
  $str .= "{$k}[{$v}]";
 }
 return $str;
 }
}

用法

$obj = new TimeCost();
$token = 'test_a';
$obj->addCost($token);
some_code();

$obj->closeCost($token);
$reslut = $obj->getString($token);

说明

1、时间精度: 默认是保留了6位, 已经足够了, 想要更高精度, 可以在new对象的时候指定$scale参数

2、token: token是为了表示某段代码, 对应的结果会以key(token), value的形式写入到record数组中。

所以用一个token多次进行addCost和closeClost的结果会进行累积。

3、getString: 传递token则返回token对应的结果, 默认会将record中的所有结果拼接返回。

感谢各位的阅读!关于“PHP如何实现记录代码运行时间封装类”这篇文章就分享到这里了,希望以上内容可以对大家有一定的帮助,让大家可以学到更多知识,如果觉得文章不错,可以把它分享出去让更多的人看到吧!

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

php
AI