萬盛學電腦網

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

PHP 精準測量函數執行時間:microtime 與效能分析工具

前言

測量代碼執行時間是效能優化第一步。PHP 提供 microtime(true) 獲取微秒級時間戳,本文示範基礎計時、統計多次執行、以及專業分析工具 Xdebug/Blackfire/XHProf。

基礎計時模式

<?php
// 1. 單次測量
$start = microtime(true);
// 待測代碼
$hash = hash('sha256', str_repeat('x', 10000));
$elapsed = microtime(true) - $start;
echo "耗時: $elapsed 秒 (" . ($elapsed * 1e6) . " 微秒)\n";

// 2. 封裝為可複用函數
function timeIt(callable $fn, int $iterations = 1): array {
    $times = [];
    for ($i = 0; $i < $iterations; $i++) {
        $start = microtime(true);
        $result = $fn();
        $times[] = microtime(true) - $start;
    }
    return [
        'min' => min($times),
        'max' => max($times),
        'avg' => array_sum($times) / count($times),
        'total' => array_sum($times),
        'result' => $result ?? null,
    ];
}

// 使用
$stats = timeIt(function() {
    return md5('long string for testing performance measurement');
}, 1000);

printf("Min: %.6fms, Max: %.6fms, Avg: %.6fms\n",
    $stats['min'] * 1000, $stats['max'] * 1000, $stats['avg'] * 1000);
?>

對比測試範例

<?php
$funcs = [
    'md5' => fn() => md5('test'),
    'sha1' => fn() => sha1('test'),
    'hash_sha256' => fn() => hash('sha256', 'test'),
    'json_encode' => fn() => json_encode(['a'=>1,'b'=>2]),
    'serialize' => fn() => serialize(['a'=>1,'b'=>2]),
];

foreach ($funcs as $name => $fn) {
    $stats = timeIt($fn, 50000);
    printf("%-15s: Avg %.4f ms | Total %.2f ms\n", $name, $stats['avg']*1000, $stats['total']*1000);
}

/*
輸出範例:
md5            : Avg 0.0012 ms | Total 60.23 ms
sha1           : Avg 0.0015 ms | Total 75.11 ms
hash_sha256    : Avg 0.0021 ms | Total 105.44 ms
json_encode    : Avg 0.0035 ms | Total 174.22 ms
serialize      : Avg 0.0042 ms | Total 210.05 ms
*/
?>

記憶體使用量測量

<?php
$startMem = memory_get_usage();
// 代碼...
$endMem = memory_get_usage();
echo "記憶體增長: " . ($endMem - $startMem) / 1024 . " KB\n";
echo "峰值記憶體: " . memory_get_peak_usage(true) / 1024 / 1024 . " MB\n";
?>

專業分析工具 (生產級優化必備)

工具類型特點安裝
XdebugProfiling + Debug生成 cachegrind 文件,配合 KCacheGrind/QCacheGrind 視覺化調用圖、火焰圖pecl install xdebug
BlackfireSaaS Profiling零侵入、生產環境安全、比對報告、CI/CD 整合註冊帳號 + Agent 安裝
XHProf輕量 ProfilingFacebook 開源、功能較簡單、適合快速排查pecl install xhprof
TidewaysAPM + Profiling生產級監控、自動異常檢測Composer 安裝

Xdebug 快速上手

; php.ini
zend_extension=xdebug.so
xdebug.mode=profile
xdebug.output_dir=/tmp/xdebug
xdebug.start_with_request=trigger

# 瀏覽器安裝 Xdebug Helper 擴展,點擊 "Profile" 重新整理頁面
# 分析生成的 cachegrind.out.xxx 文件

微基準測試避坑指南

  1. 預熱:首次執行含 JIT 編譯/OpCache 載入,捨棄前 N 次結果。
  2. 隔離:單獨腳本運行,避免其他邏輯干擾。
  3. 足夠迭代:確保總時間 > 1 秒,減少系統抖動影響。
  4. 禁用 GC:gc_disable() 測試純算力,結束後 gc_enable()。
  5. 關注中位數/百分位:平均值易受極值影響,P99 更反映真實體驗。
copyright © 萬盛學電腦網 all rights reserved