<?php
$start = microtime(true);
// ... 待測程式碼 ...
$elapsed = microtime(true) - $start;
echo "耗時: " . round($elapsed * 1000, 3) . " ms\n";
<?php
require_once 'Benchmark/Timer.php';
$timer = new Benchmark_Timer(true); // true = 自動啟動
$timer->setMarker('boot'); // 標記點
// ... 初始化代碼 ...
$timer->setMarker('db_connect');
// ... 資料庫查詢 ...
$timer->setMarker('render');
// ... 模板渲染 ...
$timer->stop();
$timer->display(); // 輸出格式化表格
輸出範例:
marker time index ex time perct ---------------------------------------- Start 123.456789 - 0.00% boot 123.457012 0.000223 1.23% db_connect 123.459876 0.002864 15.80% render 123.462345 0.002469 13.62% Stop 123.463000 0.000655 3.61% Total - 0.018111 100.00%
<?php
function profiler($dump = false) {
static $profile = [];
if ($dump) { $tmp = $profile; unset($profile); return $tmp; }
$profile[] = microtime(true);
}
register_tick_function('profiler');
profiler(); // 初始化
declare(ticks=2) { // 每 2 句觸發一次
for ($i = 0; $i < 1000; $i++) {
md5($i);
}
}
print_r(profiler(true));
注意:ticks 在 PHP 7+ 已移除,生產環境請改用 Xdebug Profiler、Blackfire、Tideways 等專業工具。
| 工具 | 類型 | 適用場景 | 安裝/使用 |
|---|---|---|---|
| Xdebug + Webgrind/KCacheGrind | 剖析器 | 開發環境函數級調用圖、耗時分佈 | pecl install xdebug; php.ini: xdebug.mode=profile |
| Blackfire.io | SaaS 剖析 | 生產環境安全剖析、CI/CD 整合、效能回歸偵測 | 註冊帳號、安裝 Agent/Probe |
| Tideways | APM/剖析 | 自建 APM、低開銷、支援分散式追蹤 | composer require tideways/phpx |
| PHPStan / Psalm | 靜態分析 | 編譯期發現型別錯誤、死代碼、效能反模式 | composer require --dev phpstan/phpstan |
# 1000 請求,20 並發
ab -n 1000 -c 20 https://your-site.com/api/test
# 關鍵指標
Requests per second: 1250.34 [#/sec] (mean)
Time per request: 16.000 [ms] (mean, across all concurrent)
Transfer rate: 2.45 [MB/sec] received
適用:單一端點吞吐量基準、優化前後對比。
# 同時 50 用戶,持續 60 秒,從 URL 清單讀取
siege -c 50 -t 60s -f urls.txt
# 關鍵指標
Transactions: 45231 hits
Availability: 100.00 %
Elapsed time: 59.87 secs
Data transferred: 12.34 MB
Response time: 0.06 secs
Transaction rate: 755.50 trans/sec
Throughput: 0.21 MB/sec
Concurrency: 49.87
Successful transactions: 45231
Failed transactions: 0
Longest transaction: 0.45
Shortest transaction: 0.01
適用:尋找系統極限 (CPU/記憶體/連接數/磁碟 IO 瓶頸)、驗證自動擴容策略。
# wrk (Lua 腳本支援複雜場景)
wrk -t4 -c100 -d30s -s post.lua https://api.site.com
# vegeta (Go 編寫、恆定速率、極高並發)
echo "GET https://api.site.com" | vegeta attack -rate=1000 -duration=30s | vegeta report
PHP 5.5+ 內建 Zend OPcache,編譯後的 Opcode 存入共享記憶體,免去重複編譯。
; php.ini 生產環境推薦配置
opcache.enable=1
opcache.enable_cli=1
opcache.memory_consumption=256
opcache.interned_strings_buffer=16
opcache.max_accelerated_files=20000
opcache.revalidate_freq=0 ; 0 = 生產環境不檢查時間戳,需部署時重啟 PHP-FPM
opcache.fast_shutdown=1
opcache.save_comments=1 ; 註解保留 (Doctrine/Annotation 需要)
opcache.validate_timestamps=0 ; 配合 revalidate_freq=0
; 開發環境設為 1, revalidate_freq=2
舊版加速器 (APC, eAccelerator, XCache) 已淘汰,PHP 7+ 僅支援 OPcache。
strpos/strstr/substr 替代簡單匹配;複雜解析用狀態機或專用解析器。classmap / optimize-autoloader,生產環境 composer dump-autoload -o。@ 運算子,改用條件判斷。