php实现毫秒
PHP 实现毫秒时间戳
在 PHP 中获取毫秒级时间戳可以通过以下方法实现:
方法一:使用 microtime 函数

function getMillisecond() {
list($microsec, $sec) = explode(" ", microtime());
return (float)sprintf('%.0f', (floatval($microsec) + floatval($sec)) * 1000);
}
echo getMillisecond();
方法二:PHP 7.1+ 使用 DateTime 对象

$date = new DateTime();
echo $date->format('Uv'); // 'U' 是秒时间戳,'v' 是毫秒部分
方法三:使用 hrtime 函数(PHP 7.3+)
$nanoseconds = hrtime(true);
$milliseconds = $nanoseconds / 1e6; // 转换为毫秒
echo (int)$milliseconds;
注意事项
- 方法一和方法二的结果可能受系统时间影响,如果系统时间被修改,返回值也会变化。
- 方法三的
hrtime是高精度时间,不受系统时间影响,适合性能测量等场景。 - 在 32 位系统上,大整数可能会溢出,需要注意处理。
性能比较场景
如果需要测量代码执行时间,推荐使用 hrtime:
$start = hrtime(true);
// 被测代码
$end = hrtime(true);
$duration = ($end - $start) / 1e6; // 毫秒
echo "执行耗时: {$duration} 毫秒";






