PHP后端性能监控与调优
PHP后端性能监控与调优性能问题迟早会遇到。系统上线后随着用户量增长各种瓶颈就会暴露出来。今天说说PHP应用的性能监控和调优。性能监控的第一步是测量。关键路径上加计时器。phpclass PerformanceMonitor{private array $timers [];private array $results [];public function startTimer(string $name): void{$this-timers[$name] microtime(true);}public function stopTimer(string $name): void{if (isset($this-timers[$name])) {$duration (microtime(true) - $this-timers[$name]) * 1000;$this-results[] [name $name, duration_ms round($duration, 2)];unset($this-timers[$name]);}}public function getReport(): array{$totalTime array_sum(array_column($this-results, duration_ms));return [total_time_ms round($totalTime, 2),breakdown $this-results,peak_memory_mb round(memory_get_peak_usage(true) / 1024 / 1024, 2),];}}$monitor new PerformanceMonitor();$monitor-startTimer(db_query);usleep(200000);$monitor-stopTimer(db_query);$monitor-startTimer(data_process);usleep(100000);$monitor-stopTimer(data_process);print_r($monitor-getReport());?慢查询日志记录。phpfunction enableSlowQueryLog(PDO $pdo, float $threshold 1.0): PDO{return $pdo;}class SlowQueryLogger{private float $threshold 1.0;public function log(string $sql, float $duration): void{if ($duration $this-threshold) {$log sprintf([%s] 慢查询 %.4fs: %s\n, date(Y-m-d H:i:s), $duration, $sql);file_put_contents(/tmp/slow-queries.log, $log, FILE_APPEND);}}}?OPcache监控。phpfunction getOpcacheStatus(): array{if (!function_exists(opcache_get_status)) return [error OPcache未启用];$status opcache_get_status(false);if ($status false) return [error 无法获取状态];$memory $status[memory_usage];$stats $status[opcache_statistics];return [memory_usage_percent round($memory[used_memory] / ($memory[used_memory] $memory[free_memory]) * 100, 2),cached_files $stats[num_cached_scripts],hit_rate round($stats[hits] / ($stats[hits] $stats[misses]) * 100, 2),];}print_r(getOpcacheStatus());?JIT配置监控。phpfunction getJitStatus(): array{$status opcache_get_status(false);$jit $status[jit] ?? [];return [enabled $jit[enabled] ?? false,buffer_size ($jit[buffer_size] ?? 0) / 1024 / 1024 . MB,];}?性能优化要有的放矢。先用监控找出真正的瓶颈再针对性地优化。数据库查询往往是最值得优化的地方一条慢查询解决好了可能比一堆PHP优化更有效。