性能优化的第一步:找到瓶颈在哪里。
为什么需要性能分析
盲目优化 = 浪费时间
猜测:可能是数据库慢
实际:是某个循环里的文件读取
正确流程:
1. 性能分析找瓶颈
2. 针对性优化
3. 验证效果
Xhprof 性能分析
安装
# 安装扩展
pecl install xhprof
# 启用扩展
echo"extension=xhprof.so" >> /etc/php.ini
echo"xhprof.output_dir=/tmp/xhprof" >> /etc/php.ini
# 重启 PHP-FPM
systemctl restart php-fpm
使用
<?php
// 开始分析
xhprof_enable(XHPROF_FLAGS_CPU + XHPROF_FLAGS_MEMORY);
// 你的代码
$users = User::with('posts')->get();
foreach ($users as $user) {
echo $user->name;
}
// 结束分析
$data = xhprof_disable();
// 保存数据
$xhprof_runs = new XHProfRuns_Default();
$run_id = $xhprof_runs->save_run($data, "myapp");
echo"http://xhprof.local/index.php?run={$run_id}&source=myapp";
分析报告
Function Name Calls Time(ms) Memory(KB)
=====================================================
main() 1 1250 2048
User::with() 1 850 1024
DB::query() 100 750 512
json_encode() 50 80 256
Blackfire 性能分析
安装
# 安装 Agent
wget -O - https://packages.blackfire.io/gpg.key | apt-key add -
echo"deb http://packages.blackfire.io/debian any main" > /etc/apt/sources.list.d/blackfire.list
apt-get update
apt-get install blackfire-agent blackfire-php
# 配置
blackfire-agent --register
blackfire config
使用
# 命令行分析
blackfire run php script.php
# Web 分析(浏览器插件)
# 安装 Chrome/Firefox 插件后,点击按钮即可
Laravel 集成
<?php
// 安装
composer require blackfire/php-sdk
// 使用
useBlackfire\Client;
useBlackfire\Profile\Configuration;
$blackfire = new Client();
$config = new Configuration();
$config->setTitle('My Profile');
$probe = $blackfire->createProbe($config);
// 你的代码
$users = User::all();
$blackfire->endProbe($probe);
Tideways 性能监控
安装
# 安装扩展
pecl install tideways_xhprof
# 配置
echo"extension=tideways_xhprof.so" >> /etc/php.ini
echo"tideways.auto_start=1" >> /etc/php.ini
使用
<?php
tideways_xhprof_enable(TIDEWAYS_XHPROF_FLAGS_MEMORY | TIDEWAYS_XHPROF_FLAGS_CPU);
// 你的代码
processData();
$data = tideways_xhprof_disable();
// 分析数据
foreach ($data as $func => $metrics) {
echo"{$func}: {$metrics['wt']}μs\n";
}
PHP 内置性能分析
microtime 计时
<?php
$start = microtime(true);
// 你的代码
sleep(1);
$end = microtime(true);
$time = ($end - $start) * 1000;
echo"执行时间: {$time}ms\n";
memory_get_usage 内存
<?php
$start_memory = memory_get_usage();
// 你的代码
$data = range(1, 100000);
$end_memory = memory_get_usage();
$used = ($end_memory - $start_memory) / 1024;
echo"内存使用: {$used}KB\n";
封装性能监控类
<?php
classProfiler
{
privatestaticarray $timers = [];
privatestaticarray $memories = [];
publicstaticfunctionstart(string $name): void
{
self::$timers[$name] = microtime(true);
self::$memories[$name] = memory_get_usage();
}
publicstaticfunctionend(string $name): array
{
$time = (microtime(true) - self::$timers[$name]) * 1000;
$memory = (memory_get_usage() - self::$memories[$name]) / 1024;
return [
'time' => round($time, 2) . 'ms',
'memory' => round($memory, 2) . 'KB',
];
}
publicstaticfunctionreport(): void
{
foreach (self::$timers as $name => $start) {
$result = self::end($name);
echo"{$name}: {$result['time']}, {$result['memory']}\n";
}
}
}
// 使用
Profiler::start('database');
$users = User::all();
$result = Profiler::end('database');
// database: 125.50ms, 2048.00KB
Laravel Debugbar
安装
composer require barryvdh/laravel-debugbar --dev
配置
// config/app.php
'providers' => [
Barryvdh\Debugbar\ServiceProvider::class,
],
// .env
DEBUGBAR_ENABLED=true
功能
APM 应用性能监控
New Relic
# 安装
wget -O - https://download.newrelic.com/548C16BF.gpg | apt-key add -
echo"deb http://apt.newrelic.com/debian/ newrelic non-free" > /etc/apt/sources.list.d/newrelic.list
apt-get update
apt-get install newrelic-php5
# 配置
newrelic-install install
Datadog
# 安装
composer require datadog/php-datadogstatsd
# 使用
use DataDog\DogStatsd;
$statsd = new DogStatsd();
$statsd->increment('page.views');
$statsd->timing('database.query', 150);
性能分析最佳实践
常见性能瓶颈
// ❌ N+1 查询
$users = User::all();
foreach ($users as $user) {
echo $user->posts->count(); // 每次查询
}
// ✅ 预加载
$users = User::with('posts')->get();
foreach ($users as $user) {
echo $user->posts->count(); // 不查询
}
// ❌ 循环里查询
for ($i = 0; $i < 100; $i++) {
$user = User::find($i);
}
// ✅ 批量查询
$users = User::whereIn('id', range(1, 100))->get();
// ❌ 大数组操作
$data = range(1, 1000000);
$result = array_map(fn($n) => $n * 2, $data);
// ✅ 生成器
functiongenerate(){
for ($i = 1; $i <= 1000000; $i++) {
yield $i * 2;
}
}
总结
性能优化流程:
1. 使用工具找瓶颈
2. 针对性优化
3. 验证效果
4. 持续监控
推荐工具:
- 开发:Laravel Debugbar
- 分析:Xhprof / Blackfire
- 监控:New Relic / Datadog
性能优化不是猜测,而是数据驱动的科学过程。