首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 網頁程式設計 >> PHP 程式設計 >> PHP 相關知識

PHP 獲取當前毫秒級時間戳的正確姿勢(microtime、hrtime、浮點數精度)

     編輯:PHP 相關知識

核心函式:microtime()

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', ...)?

  • 浮點數精度限制:PHP 浮點數為 IEEE 754 雙精度(53 位元有效數字),毫秒時間戳約 13 位數(如 1699999999123),仍在精確整數範圍內(2^53 ≈ 9e15),直接 (int) 強制轉換即可,無需 sprintf。
  • hrtime(true) 回傳浮點數奈秒,精度更高,轉毫秒同樣安全。

32 位元系統特別說明

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、字串拆解寫法,簡潔、高效、精度安全。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved