php 程序运行时间调试工具类封装

2021-11-22  本文已影响0人  黄刚刚

前言

今天发现我们的某一个接口响应时间很长,接口中执行的代码片段也很多,想分别看看不同的代码片段分别所执行的时间,所以就封装了下面的这个类,也很方便使用。

源码

<?php
declare (strict_types=1);

namespace app\util;

/**
 * 程序运行时间调试工具类
 * 主要用途是获取程序在指定代码片段说花费的时间
 * @example 请参考example方法
 *
 * @author hcg
 * @email 532508307@qq.com
 */
class RunTimer
{
    // 程序运行开始时间
    private $StartTime = 0;
    // 程序运行结束时间
    private $StopTime = 0;
    // 程序运行花费时间
    private $TimeSpent = 0;

    // 程序运行开始
    public function start()
    {
        $this->StartTime = microtime(true);
    }

    // 程序运行结束
    public function stop()
    {
        $this->StopTime = microtime(true);
    }

    // 程序运行花费的时间
    public function spent()
    {
        // 返回获取到的程序运行时间差
        $this->TimeSpent = $this->StopTime - $this->StartTime;
        echo "程序运行时间为:".number_format($this->TimeSpent * 1000, 4) . "毫秒\r\n";
    }

    // 本调试程序的一个常规使用示例
    public static function example(){
        // 实例化
        $timer = new RunTimer();
        $timer->start();

        #需要执行的代码,我们这里简单的睡眠2秒,代表程序执行花费了2秒
        sleep(2);

        $timer->stop();
        $timer->spent();
    }
}
上一篇 下一篇

猜你喜欢

热点阅读