測量代碼執行時間是效能優化第一步。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";
?>
| 工具 | 類型 | 特點 | 安裝 |
|---|---|---|---|
| Xdebug | Profiling + Debug | 生成 cachegrind 文件,配合 KCacheGrind/QCacheGrind 視覺化調用圖、火焰圖 | pecl install xdebug |
| Blackfire | SaaS Profiling | 零侵入、生產環境安全、比對報告、CI/CD 整合 | 註冊帳號 + Agent 安裝 |
| XHProf | 輕量 Profiling | Facebook 開源、功能較簡單、適合快速排查 | pecl install xhprof |
| Tideways | APM + Profiling | 生產級監控、自動異常檢測 | Composer 安裝 |
; 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 文件
gc_disable() 測試純算力,結束後 gc_enable()。