php使用register_tick_function来定位执行慢的代码

slow_code_time = $time;
        return $this;
    }

    /**
     * startCollect
     * @throws Exception
     */
    public function startCollect()
    {
        declare (ticks=1);
        if (!register_tick_function([$this, 'handle'])) {
            throw new \Exception('注册tracker处理函数失败');
        }
    }

    /**
     * handle
     */
    public function handle()
    {
        // 记录执行代码次数+1
        $this->eval_code_line_num++;
        // 获取当前时间(毫秒时间戳)
        $millisecondTime = $this->millisecondTime();
        // 记录执行代码开始时间(毫秒时间戳)
        if (!$this->eval_code_time) {
            $this->eval_code_time = $millisecondTime;
        }
        // 当前时间 - 执行代码开始时间 > 执行代码过慢时间 : 说明执行当前行的代码执行过慢
        if (($millisecondTime - $this->eval_code_time) > $this->slow_code_time) {
            $e = new \Exception();
            $ret = $e->getTrace()[0] ?? [];
            $ret['eval_code_line_num'] = $this->eval_code_line_num;
            var_dump($ret);
            die();
        } else {
            $this->eval_code_time = $millisecondTime;
        }
    }
}

// 在其他文件中的使用示例 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
/*
// 引入代码执行时间跟踪器类
include_once "./Tracker.php";
// 设置执行指令ticks=1(这个一定不能少)
declare(ticks=1);
// 查询执行超过10毫秒的代码位置
$object = new Tracker();
$object->setSlowCodeTime(10)->startCollect();

// 写个循环100次
for ($i = 1;$i <= 100;$i++){
    if($i == 10){
        // 延迟10毫秒(usleep函数的值是微妙,1000微妙=1毫秒)
        usleep(10000);
    }
}
*/

你可能感兴趣的:(php使用register_tick_function来定位执行慢的代码)