当前位置:网站首页>php microtime 封装工具类,计算接口运行时间(打断点)
php microtime 封装工具类,计算接口运行时间(打断点)
2022-08-03 12:04:00 【倾听岁月】
引言
当我们开发完自己负责板块的相关业务程序,然后发布到线上后出了问题。然后做问题排查的时候,发现是接口运行超时的问题。所以我们需要通过某个途径去知晓这个接口每个工作环节的执行时间。本文根据我的想法和经验,设计了一个工具类,通过这个工具类,我们可以知晓各个工作环节的运行时间。
php本身有提供一个函数microtime,通过这个函数并配合我们打断点。我们就能知道程序运行时各个地方的耗时。
样例
本样例适用于php-fpm模式或cli模式,如果你采用的swoole-work 请考虑脏数据的问题(swoole-work 常驻内存,多个线程共享内存)
封装microtime,设计一个断点类
Point.php
<?php
namespace App\Components\Util;
class Point
{
//初始时间
public float $startTime;
//StdClass 是 php当中的空类,但不是所有类的基类,相关内容请自行百度
public \StdClass $runTimes;
public function __construct()
{
//初始化当前时间
$this->startTime = microtime(true);
//初始化一个空类
$this->runTimes = new \StdClass;
}
public function addPoint(string $pointName)
{
//统计断点时间
$this->runTimes->{$pointName} = microtime(true);
}
//断点时间计算
public function calculation()
{
//初始化一个空类来统计
$data = new \StdClass;
//断点时间计算
if(!empty($this->runTimes))
{
foreach((array)$this->runTimes as $k=>$v)
{
$data->{$k} = number_format(bcsub($v , $this->startTime,4) * 1000,4) . "毫秒";
}
}
return $data;
}
}
关于断点类的使用
public function index14()
{
$runTime = new Point();
/**
* @var Test3 $test3
*/
$test3 = app()->make(Test3::class);
//断点-1
$runTime->addPoint("test3_run");
$userinfo = $test3->userService->get(867076808);
//断点-2
$runTime->addPoint("user_service_get");
$this->info($userinfo->username);
//断点-3
$runTime->addPoint("print");
//打印断点执行时间
dd($runTime->calculation());
}
输出结果
wsyUMcKjfP
{
+"test3_run": "9.8000毫秒"
+"user_service_get": "27.5000毫秒"
+"print": "27.9000毫秒"
}
一般我们常用于将这个辅助类去检测
restFule接口的耗时
某个类方法的执行耗时
mysql连接耗时
mysql CURD操作耗时
redis连接耗时
redis查询耗时
读写文件耗时
业务程序执行耗时
根据程序的执行情况,我们就知晓各个工作单元的执行时间,然后设计优化方案。
如果你觉得不错,给个关注和好评吧~
边栏推荐
- FE主导打造一个运营活动平台
- 零拷贝、MMAP、堆外内存,傻傻搞不明白...
- 【MySQL功法】第2话 · 数据库与数据表的基本操作
- CDH6.3.2开启kerberos认证
- [深入浅出]三位数排序
- OFDM 十六讲 4 -What is a Cyclic Prefix in OFDM
- Blazor Server(6) from scratch--policy-based permission verification
- 5个超好用手机开源自动化工具,哪个适合你?
- I in mother's womb SOLO20 years
- 4500 words sum up, a software test engineer need to master the skill books
猜你喜欢
随机推荐
LyScript 实现对内存堆栈扫描
LeetCode——1161. 最大层内元素和
-找树根-
距LiveVideoStackCon 2022 上海站开幕还有3天!
RTP协议分析
fastposter v2.9.0 程序员必备海报生成器
R语言ggplot2可视化:使用ggpubr包的ggsummarystats函数可视化箱图(通过ggfunc参数设置)、在可视化图像的下方添加描述性统计结果表格
How to do App Automation Testing?Practical sharing of the whole process of App automation testing
【云原生 · Kubernetes】部署Kubernetes集群
分享一款实用的太阳能充电电路(室内光照可用)
常用lambda表达式
pandas连接oracle数据库并拉取表中数据到dataframe中、筛选当前时间(sysdate)到一天之前的所有数据(筛选一天范围数据)
漫谈缺陷管理的自动化实践方案
LyScript implements memory stack scanning
The effects of the background and the Activiti
FE主导打造一个运营活动平台
4500 words sum up, a software test engineer need to master the skill books
小身材有大作用——光模块寿命分析(二)
第5章 实现首页Tab数据展示
QGIS绘制演习区域示意图









