php实现计时功能
使用 time() 函数获取时间戳
在 PHP 中,可以通过 time() 函数获取当前的 Unix 时间戳(自 1970 年 1 月 1 日以来的秒数)。记录开始和结束时间戳,计算差值即可实现计时功能。

$start = time();
// 执行需要计时的代码
sleep(2); // 模拟耗时操作
$end = time();
$duration = $end - $start;
echo "耗时: {$duration} 秒";
使用 microtime() 获取微秒级精度
如果需要更高精度的计时(毫秒或微秒),可以使用 microtime(true) 函数。该函数返回当前时间的微秒数,参数设为 true 时返回浮点数而非字符串。

$start = microtime(true);
// 执行需要计时的代码
usleep(2000); // 模拟耗时操作(2000 微秒)
$end = microtime(true);
$duration = $end - $start;
echo "耗时: " . round($duration * 1000, 2) . " 毫秒";
封装为可复用的计时器类
可以封装一个简单的计时器类,方便在多个地方复用。以下是一个示例实现:
class Timer {
private $startTime;
private $endTime;
public function start() {
$this->startTime = microtime(true);
}
public function stop() {
$this->endTime = microtime(true);
}
public function getDuration($precision = 2) {
return round(($this->endTime - $this->startTime) * 1000, $precision);
}
}
// 使用示例
$timer = new Timer();
$timer->start();
// 执行需要计时的代码
sleep(1);
$timer->stop();
echo "耗时: " . $timer->getDuration() . " 毫秒";
使用 hrtime() 获取纳秒级精度(PHP 7.3+)
对于需要纳秒级精度的场景,可以使用 hrtime() 函数。该函数返回高分辨率时间,适合性能分析等需求。
$start = hrtime(true);
// 执行需要计时的代码
usleep(1000); // 模拟耗时操作
$end = hrtime(true);
$duration = ($end - $start) / 1e6; // 转换为毫秒
echo "耗时: " . round($duration, 2) . " 毫秒";
注意事项
- 计时精度受系统限制,尤其在虚拟化环境中可能不如物理机准确。
- 长时间运行的脚本需注意
time()和microtime()的溢出问题(32 位系统下 2038 年问题)。 - 生产环境中建议结合日志系统记录耗时,而非直接输出到页面。






