PHP 內建 microtime() 回傳「秒數 微秒數」字串,或 microtime(true) 直接回傳浮點數秒數(含微秒小數)。
/**
* 取得當前毫秒級時間戳(整數)
* @return int 毫秒數(自 Unix 紀元起)
*/
function getMillisecond(): int {
// PHP 7.3+ 推薦:hrtime() 高解析度奈秒計時器,避免浮點精度問題
if (function_exists('hrtime')) {
return (int) (hrtime(true) / 1_000_000); // 奈秒轉毫秒
}
// 相容舊版:microtime(true) * 1000
return (int) (microtime(true) * 1000);
}
sprintf('%.0f', ...)?1699999999123),仍在精確整數範圍內(2^53 ≈ 9e15),直接 (int) 強制轉換即可,無需 sprintf。hrtime(true) 回傳浮點數奈秒,精度更高,轉毫秒同樣安全。32 位元 PHP 整數上限 2^31-1 = 2,147,483,647(約 1901 年前),毫秒時間戳早已超過,**必須用浮點數或字串儲存**,但現代生產環境幾乎全為 64 位元,(int) 完全安全。
$ms = getMillisecond();
$sec = (int)($ms / 1000);
$milli = $ms % 1000;
echo date('Y-m-d H:i:s', $sec) . sprintf('.%03d', $milli);
// 2024-01-15 14:30:45.123
| 方法 | 呼叫成本 | 精度 | 推薦場景 |
|---|---|---|---|
time() | 極低 | 秒 | 日誌時間戳、快取過期 |
microtime(true) | 低 | 微秒 | 執行時間測量、一般毫秒需求 |
hrtime(true) | 低 | 奈秒 | PHP 7.3+、高精度計時、基準測試 |
DateTime::createFromFormat('U.u') | 高 | 微秒 | 需物件操作、時區處理時 |
microtime() 回傳毫秒:實為微秒(百萬分之一秒),需 * 1000 轉毫秒。date('u') 取得毫秒:date('u') 永遠回傳 000000,因 date() 接受整數秒數。需用 DateTime::format('u') 或 microtime()。$end - $start > $threshold 而非 ==。現代 PHP(7.3+)請直接使用 hrtime(true) / 1_000_000 獲取毫秒整數,舊版用 (int)(microtime(true) * 1000)。拋棄複雜的 sprintf、字串拆解寫法,簡潔、高效、精度安全。