萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> PHP 程式設計

PHP 取得毫秒級時間戳:microtime() 高精度計時與效能測量實戰

為什麼 PHP 沒有內建毫秒時間戳函數?

PHP 歷史設計以秒級 time() 為主,微秒級需用 microtime() 組合。PHP 7.1+ 引入 hrtime()(高解析度奈秒計時器),現代開發應優先使用 hrtime() 進行效能測量,microtime() 用於兼容性需求或人類可讀時間戳。

三種取得毫秒時間戳的方法對比

方法精度回傳類型適用場景PHP 版本
microtime(true)微秒float(秒.微秒)日誌時間戳、緩存過期、一般計時全版本
(int)(microtime(true) * 1000)毫秒int(13 位)JS 互操作、資料庫毫秒欄位、追蹤 ID全版本
hrtime(true)奈秒int(奈秒)效能基準測試、高精度計時7.3+

microtime() 經典用法與陷阱

<?php
// 1. 浮點數秒(含微秒小數)
$timeFloat = microtime(true); // 1705315200.123456

// 2. 毫秒整數(13 位,JS Date.now() 相容)
$ms = (int)round(microtime(true) * 1000); // 1705315200123
// 或
$ms = (int)(microtime(true) * 1000); // 截斷,不四捨五入

// 3. 陣列形式(舊式寫法)
list($usec, $sec) = explode(' ', microtime());
$msOld = (int)(($sec + $usec) * 1000);

// ⚠️ 陷阱:float 精度限制
// PHP float 為 IEEE 754 雙精度(53 位有效位數)
// 當前毫秒時間戳 ~1.7e12,仍在精確整數範圍內(2^53 ≈ 9e15)
// 但進行運算時可能產生浮點誤差,建議用 round() 或 hrtime()
?>

hrtime():現代高精度計時器(推薦效能測量)

<?php
// 取得奈秒級時間戳(自系統啟動或任意基準)
$start = hrtime(true); // int: 奈秒

// 執行待測代碼
usleep(1000); // 1ms

$end = hrtime(true);
$elapsedNs = $end - $start; // 奈秒差值
$elapsedMs = $elapsedNs / 1_000_000; // 毫秒
$elapsedSec = $elapsedNs / 1_000_000_000; // 秒

echo "耗時:{$elapsedMs} ms ({$elapsedSec} s)\n";

// 取得奈秒時間戳(非單調時鐘,僅供參考)
$nsTimestamp = hrtime(false); // [秒, 奈秒] 陣列
?>

效能測量最佳實踐:Benchmark 類

<?php
class Benchmark
{
    private int $startNs;
    private array $marks = [];
    private string $label;

    public function __construct(string $label = '')
    {
        $this->label = $label;
        $this->start();
    }

    public function start(): void
    {
        $this->startNs = hrtime(true);
        $this->marks = [];
    }

    public function mark(string $name): float
    {
        $now = hrtime(true);
        $elapsedMs = ($now - $this->startNs) / 1_000_000;
        $this->marks[$name] = $elapsedMs;
        return $elapsedMs;
    }

    public function measure(string $name, callable $fn): mixed
    {
        $markStart = hrtime(true);
        $result = $fn();
        $markEnd = hrtime(true);
        $elapsedMs = ($markEnd - $markStart) / 1_000_000;
        $this->marks[$name] = $elapsedMs;
        return $result;
    }

    public function getReport(): array
    {
        return [
            'label' => $this->label,
            'total_ms' => ($this->marks['__total'] ?? (hrtime(true) - $this->startNs) / 1_000_000),
            'marks' => $this->marks,
        ];
    }

    public function __destruct()
    {
        if (!$this->marks) return;
        $report = $this->getReport();
        error_log("[Benchmark {$report['label']}] Total: {$report['total_ms']}ms, Marks: " . json_encode($report['marks']));
    }
}

// 使用範例
$bench = new Benchmark('UserDashboard');
$user = $bench->measure('db_query', fn() => User::find(1));
$bench->measure('template_render', fn() => view('dashboard', ['user' => $user]));
$bench->mark('total');
?>

格式化人類可讀時間戳(含毫秒)

<?php
function formatDateTimeWithMs(int $msTimestamp = null, string $format = 'Y-m-d H:i:s.u'): string
{
    $msTimestamp ??= (int)round(microtime(true) * 1000);
    $seconds = (int)($msTimestamp / 1000);
    $milliseconds = $msTimestamp % 1000;
    
    $dt = new DateTime("@{$seconds}");
    $dt->setTimezone(new DateTimeZone(date_default_timezone_get()));
    
    // 手動插入毫秒(u 為微秒,需補 3 位)
    return $dt->format(str_replace('u', sprintf('%03d', $milliseconds), $format));
}

echo formatDateTimeWithMs(); // 2024-01-15 14:30:45.123
?>

資料庫儲存建議

資料庫欄位類型PHP 寫入備註
MySQL 5.6.4+DATETIME(3) / TIMESTAMP(3)date('Y-m-d H:i:s.u', $ms/1000)毫秒精度,TIMESTAMP 含時區轉換
PostgreSQLTIMESTAMP(3) WITH TIME ZONEDateTime::createFromFormat('U.u', ...)原生支援微秒
MongoDBDate (BSON DateTime)new MongoDB\BSON\UTCDateTime($ms)內部為毫秒
RedisString (毫秒字串) / Sorted Set score$redis->zAdd('events', $ms, $data)Score 為 double,精度足夠

分散式追蹤 ID 生成(雪花演算法簡化版)

<?php
function generateTraceId(int $workerId = 1): string
{
    // 41bit 毫秒時間戳 + 10bit worker + 12bit sequence
    // 簡化版:毫秒時間戳(13位) + 進程ID(5位) + 隨機(4位) = 22位數字
    $ms = (int)round(microtime(true) * 1000);
    $pid = getmypid() % 32; // 5 bits
    $rand = random_int(0, 15); // 4 bits
    
    return sprintf('%d%02d%01x', $ms, $pid, $rand);
    // 範例:170531520012305a
}
?>

總結

  • 一般時間戳記錄:(int)round(microtime(true) * 1000) 取 13 位毫秒整數
  • 效能基準測試/程式碼剖析:唯一正解 hrtime(true),奈秒精度、單調時鐘、不受系統時間調整影響
  • 資料庫儲存:使用原生毫秒/微秒支援欄位(DATETIME(3)、TIMESTAMPTZ)
  • 前後端互操作:毫秒整數為標準(JS Date.now()、Java System.currentTimeMillis()、Go time.Now().UnixMilli())
copyright © 萬盛學電腦網 all rights reserved