在PHP中请求外部网址时,记录请求耗时是性能监控的基础工作。通过统计从发起请求到接收完响应的时间,我们可以判断接口是否变慢,也能为后续优化提供数据支持。下面介绍几种实用的实现方式。

使用microtime记录耗时
最简单的方式是在请求前后分别调用microtime获取时间戳,两者相减就是耗时。以file_get_contents为例:
<?php
// 记录开始时间
$start = microtime(true);
// 请求目标网址
$response = file_get_contents('https://ipipp.com/api/test');
// 记录结束时间
$end = microtime(true);
// 计算耗时(秒)
$cost = $end - $start;
echo '请求耗时:' . $cost . ' 秒';
?>
这种方法适合快速验证,但无法区分DNS解析、连接、传输等阶段的时间。
利用cURL获取详细耗时
cURL提供了curl_getinfo函数,可以拿到非常细的耗时字段,比如总耗时、连接耗时、下载耗时等。
<?php
$ch = curl_init('https://ipipp.com/api/test');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$start = microtime(true);
$result = curl_exec($ch);
$end = microtime(true);
// 获取cURL内部统计信息
$info = curl_getinfo($ch);
curl_close($ch);
echo '总耗时(自己记):' . ($end - $start) . ' 秒' . PHP_EOL;
echo 'cURL总耗时:' . $info['total_time'] . ' 秒' . PHP_EOL;
echo '连接耗时:' . $info['connect_time'] . ' 秒' . PHP_EOL;
echo '下载耗时:' . $info['download_content_length'] . ' 字节' . PHP_EOL;
?>
其中total_time是cURL自己统计的从开始到结束的时间,和我们用microtime算出来的接近。
封装一个带监控的请求函数
为了复用,可以把耗时记录封装起来,方便在项目中统一调用。
<?php
function request_with_cost($url) {
$start = microtime(true);
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$data = curl_exec($ch);
$cost = microtime(true) - $start;
$info = curl_getinfo($ch);
curl_close($ch);
return array(
'data' => $data,
'cost' => $cost,
'http_code' => $info['http_code']
);
}
$resp = request_with_cost('https://ipipp.com/api/test');
echo '状态码:' . $resp['http_code'] . ',耗时:' . $resp['cost'] . ' 秒';
?>
注意事项
- 如果请求失败,curl_exec返回false,仍应记录耗时用于排查网络问题。
- 微服务环境下建议将耗时日志写入文件或监控系统,而不是直接输出。
- 使用file_get_contents时要注意超时设置,避免慢请求拖垮整个脚本。
通过上述方法,你就能在PHP中方便地记录请求网址的耗时,并根据数据做基础的性能监控。
PHP请求耗时cURLmonitor_performancefile_get_contents修改时间:2026-07-25 05:51:19