在 PHP 開發中,精確計算程式執行時間或生成唯一標識常需要微秒級時間戳。早期開發者習慣自寫 microtime_float() 函數拆解字串再轉換,但自 PHP 5.0 起,microtime() 內建支援 get_as_float 參數,直接回傳浮點數,效能大幅提升。
function microtime_float() {
list($usec, $sec) = explode(" ", microtime());
return ((float)$usec + (float)$sec);
}
// 直接獲取浮點數時間戳
$timestamp = microtime(true);
根據官方文件,microtime([bool $get_as_float]) 若不帶參數回傳 "msec sec" 格式字串;若 $get_as_float = true 則回傳浮點數(秒.微秒)。此參數自 PHP 5.0.0 新增。
作者在 Windows XP 與 Linux 環境分別測試 10,000 次呼叫,結果顯著:
| 測試函數 | Windows XP (ms) | Linux (ms) |
|---|---|---|
| microtime_float() | 109.56 | 47.25 |
| microtime(true) | 38.82 | 9.21 |
| microtime_float2() (版本判斷) | 52.79 | 16.33 |
| microtime_float3() (直接回傳) | 45.07 | 12.28 |
結論:在 PHP 5+ 環境,直接使用 microtime(true) 最快,比傳統寫法快 2 倍以上。若需兼容舊版本,可採用 microtime_float2() 判斷 PHP_VERSION 再決定呼叫方式。
microtime(true),簡潔高效。function getMicrotimeFloat() {
if (PHP_VERSION_ID >= 50000) { // PHP 5.0.0 以上
return microtime(true);
}
list($usec, $sec) = explode(" ", microtime());
return (float)$usec + (float)$sec;
}
採用 PHP_VERSION_ID 整數比較比字串比較更可靠,推薦用於版本檢查。