本文目录导读:

我来系统性地介绍PHP的性能指标及其监控方法。
核心性能指标
执行时间
// 基础计时 $start = microtime(true); // 你的代码 $end = microtime(true); $executionTime = ($end - $start) * 1000; // 毫秒
内存使用
$memoryBefore = memory_get_usage(); // 你的代码 $memoryAfter = memory_get_usage(); $peakMemory = memory_get_peak_usage();
数据库查询性能
// 使用PDO示例
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$queryStart = microtime(true);
$result = $db->query("SELECT * FROM users");
$queryTime = microtime(true) - $queryStart;
关键性能指标(KPI)
响应时间指标
✅ 正常: < 200ms
⚠️ 警告: 200-500ms
❌ 问题: > 1000ms
内存消耗指标
- 脚本执行: < 64MB
- API请求: < 32MB
- 大型处理: < 256MB
吞吐量指标
QPS (每秒查询数)
- 小型站点: 100-500
- 中型站点: 500-2000
- 大型站点: 2000+
性能监控方案
内置监控类
class PerformanceMonitor {
private $startTime;
private $memoryStart;
private $queries = [];
public function __construct() {
$this->startTime = microtime(true);
$this->memoryStart = memory_get_usage();
}
public function getMetrics() {
return [
'execution_time' => (microtime(true) - $this->startTime) * 1000,
'memory_usage' => memory_get_usage() - $this->memoryStart,
'peak_memory' => memory_get_peak_usage(),
'query_count' => count($this->queries),
'total_query_time' => array_sum(array_column($this->queries, 'time'))
];
}
}
Xdebug 分析
; php.ini 配置 xdebug.mode=profile xdebug.output_dir=/tmp/profiler xdebug.profiler_output_name=cachegrind.out.%p
Blackfire 工具
# 安装Blackfire composer require blackfire/player # 运行性能分析 blackfire run php script.php
性能优化指标
OpCache 状态
$opcacheStatus = opcache_get_status();
$metrics = [
'hits' => $opcacheStatus['opcache_statistics']['hits'],
'misses' => $opcacheStatus['opcache_statistics']['misses'],
'cache_full' => $opcacheStatus['opcache_statistics']['oom_restarts'],
'hit_rate' => ($hits / ($hits + $misses)) * 100
];
慢查询日志
-- MySQL 慢查询配置 SET GLOBAL slow_query_log = 'ON'; SET GLOBAL long_query_time = 1; SET GLOBAL slow_query_log_file = '/var/log/mysql/slow.log';
PHP-FPM 指标
# 查看PHP-FPM状态 pm.status_path = /status # 监控指标 pool: www process manager: dynamic start time: 21/Oct/2024:10:00:00 start since: 3600 accepted conn: 15000 listen queue: 0 max listen queue: 5 listen queue len: 128 idle processes: 5 active processes: 10 total processes: 15 max active processes:20 max children reached:0 slow requests: 0
实战监控
请求级监控
class RequestMonitor {
private $startTime;
private $metrics = [];
public function start() {
$this->startTime = microtime(true);
$this->metrics['memory_start'] = memory_get_usage();
$this->metrics['queries'] = 0;
$this->metrics['query_time'] = 0;
}
public function addQuery($time) {
$this->metrics['queries']++;
$this->metrics['query_time'] += $time;
}
public function finish() {
$this->metrics['total_time'] = microtime(true) - $this->startTime;
$this->metrics['memory_peak'] = memory_get_peak_usage();
$this->metrics['memory_current'] = memory_get_usage();
// 记录到日志
$this->logMetrics();
}
private function logMetrics() {
$log = sprintf(
"Time: %.2fms | Mem: %.2fMB | Peak: %.2fMB | Queries: %d | QueryTime: %.2fms\n",
$this->metrics['total_time'] * 1000,
($this->metrics['memory_current'] - $this->metrics['memory_start']) / 1048576,
$this->metrics['memory_peak'] / 1048576,
$this->metrics['queries'],
$this->metrics['query_time'] * 1000
);
error_log($log, 3, '/var/log/php_monitor.log');
}
}
性能报警配置
class PerformanceAlert {
private $thresholds = [
'execution_time' => 1000, // 毫秒
'memory_usage' => 128 * 1024 * 1024, // 128MB
'query_count' => 100,
'query_time' => 5 // 秒
];
public function check(array $metrics) {
foreach ($this->thresholds as $metric => $threshold) {
if (isset($metrics[$metric]) && $metrics[$metric] > $threshold) {
$this->sendAlert($metric, $metrics[$metric], $threshold);
}
}
}
private function sendAlert($metric, $value, $threshold) {
// 发送邮件、短信或写入告警日志
error_log("ALERT: $metric exceeded threshold ($value > $threshold)");
}
}
最佳实践建议
性能基准
- 页面加载: < 500ms
- API响应: < 200ms
- 内存使用: < 64MB
- 数据库查询: < 50次/请求
- 文件包含: < 30个/请求
监控频率
- 线上环境: 实时监控
- 开发环境: 每次部署
- 压测环境: 每次变更
工具推荐
- APM: New Relic, Datadog
- Profiling: Xdebug, Blackfire, Tideways
- 日志: ELK Stack, Graylog
- 监控: Prometheus + Grafana
这些指标可以帮助你全面了解PHP应用的性能状况,及时发现问题并进行优化。