性能分析示例

内置性能分析器的完整 PHP 场景。性能分析指南解释了这些场景用到的触发条件和 SDK,性能分析器参考则说明了设置和文件。

每个脚本都可以放进指南中快速上手配置的 www/public/,然后用 curl 调用。

带手动控制的简单控制器

www/public/report.php
<?php declare(strict_types=1); use function OxPHP\Profile\{start, stop, mark, metric, is_active}; function fetch_rows(PDO $db, int $user_id): array { $stmt = $db->prepare('SELECT * FROM orders WHERE user_id = ? LIMIT 1000'); $stmt->execute([$user_id]); return $stmt->fetchAll(PDO::FETCH_ASSOC); } function render_report(array $rows): string { $sum = array_sum(array_column($rows, 'amount')); return json_encode(['count' => count($rows), 'total' => $sum]); } $db = new PDO('mysql:host=db;dbname=app', 'app', 'secret'); $user_id = (int) ($_GET['user_id'] ?? 1); // 只分析这段繁重的代码块,即使没有发送触发条件。 start(); mark('report.begin', ['user_id' => (string) $user_id]); $rows = fetch_rows($db, $user_id); metric('db.rows', (float) count($rows)); $body = render_report($rows); metric('response.bytes', (float) strlen($body)); mark('report.done'); stop(); header('Content-Type: application/json'); echo $body; // 可选:告知前端此请求已被分析。 if (is_active()) { header('X-Profiled: 1'); }

调用:

bash
curl -H "X-OxPHP-Profile: dev-secret" 'http://localhost/report.php?user_id=42'

带属性的服务类

www/lib/OrderService.php
<?php declare(strict_types=1); use OxPHP\Profile\{SlowThreshold, MemoryThreshold}; final class OrderService { public function __construct( private readonly PDO $db, private readonly Mailer $mailer, ) {} #[SlowThreshold(ms: 250)] public function create(array $payload): int { $this->db->beginTransaction(); try { $id = $this->insertOrder($payload); $this->insertLines($id, $payload['items']); $this->db->commit(); $this->mailer->sendReceipt($id); return $id; } catch (\Throwable $e) { $this->db->rollBack(); throw $e; } } #[MemoryThreshold(kb: 2048)] public function exportCsv(int $user_id): string { $stmt = $this->db->prepare('SELECT * FROM orders WHERE user_id = ?'); $stmt->execute([$user_id]); $buf = fopen('php://temp', 'r+'); fputcsv($buf, ['id', 'created_at', 'total']); while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) { fputcsv($buf, [$row['id'], $row['created_at'], $row['total']]); } rewind($buf); return stream_get_contents($buf); } private function insertOrder(array $p): int { /* ... */ return 0; } private function insertLines(int $id, array $items): void { /* ... */ } }

批处理作业:在 N 次迭代中只分析第一次

www/bin/import.php
<?php declare(strict_types=1); use function OxPHP\Profile\{start, stop, mark}; $files = glob('/data/incoming/*.csv'); $i = 0; foreach ($files as $path) { if ($i === 0) { start(); // 只完整分析第一个文件 mark('batch.begin', ['path' => $path]); } import_one($path); if ($i === 0) { mark('batch.first_done'); stop(); } $i++; } function import_one(string $path): void { /* ... */ }

对比两种实现

一个带性能分析的微基准测试,比较朴素实现与流式实现:

www/public/bench.php
<?php declare(strict_types=1); use function OxPHP\Profile\{start, stop, mark, metric}; function naive_sum(string $path): int { $rows = array_map('str_getcsv', file($path)); // 整个文件读入内存 return array_sum(array_column($rows, 1)); } function streaming_sum(string $path): int { $h = fopen($path, 'r'); $total = 0; while (($row = fgetcsv($h)) !== false) { $total += (int) ($row[1] ?? 0); } fclose($h); return $total; } $path = '/data/big.csv'; $which = $_GET['impl'] ?? 'naive'; start(); mark('bench.begin', ['impl' => $which]); $t0 = hrtime(true); $result = $which === 'naive' ? naive_sum($path) : streaming_sum($path); $elapsed_ms = (hrtime(true) - $t0) / 1e6; metric('bench.elapsed_ms', $elapsed_ms); metric('bench.result', (float) $result); mark('bench.done'); stop(); echo json_encode(['impl' => $which, 'elapsed_ms' => $elapsed_ms, 'result' => $result]);

两种实现各运行一次,然后取最近的两次运行,像验证优化前后的假设中那样对比它们的 .collapsed 文件:

bash
curl -H "X-OxPHP-Profile: dev-secret" "http://localhost/bench.php?impl=naive" curl -H "X-OxPHP-Profile: dev-secret" "http://localhost/bench.php?impl=streaming" curl -sH "Authorization: Bearer dev-secret" \ "http://localhost:9090/__profiler/runs?limit=2" | jq '.runs[] | .run_id'

生产代码中的条件性分析

经典场景:某个函数只对部分用户变慢。

php
<?php declare(strict_types=1); use function OxPHP\Profile\{start, stop, is_active}; function charge(User $user, Money $amount): PaymentResult { // 如果这个请求正在被分析, // 就在第三方调用内部开启额外日志。 $verbose = is_active(); $gateway = new StripeClient(verbose: $verbose); return $gateway->charge($user->id, $amount); } function oncall_path(Order $order): void { // 只分析 VIP 用户,无需外部触发条件。 if ($order->user->tier === 'vip') { start(); } process($order); if ($order->user->tier === 'vip') { stop(); } }

自我分析的冒烟检查

一个从 PHP 中开启性能分析、并报告 SDK 是否表现正常的脚本。它不需要触发条件,但性能分析器必须已启用(PROFILER_ENABLED=true),否则 start() 不会执行任何操作。调用它时不要带请求头,并且要在采样不会选中它的服务器上调用。

www/public/profile-smoke.php
<?php declare(strict_types=1); use function OxPHP\Profile\{start, stop, mark, is_active}; $checks = ['inactive at first' => !is_active()]; start(); $checks['active after start'] = is_active(); mark('smoke.midpoint'); $sum = 0; for ($i = 0; $i < 100_000; $i++) { $sum += $i; } stop(); $checks['inactive after stop'] = !is_active(); $checks['computation OK'] = $sum === 4999950000; http_response_code(in_array(false, $checks, true) ? 500 : 200); header('Content-Type: application/json'); echo json_encode($checks);

从一系列 Postman 请求中定位热点

场景:/api/search 有时慢,不是一直慢。对一次 Postman 运行中的每个请求进行分析:

javascript
// Postman 预请求脚本 pm.request.headers.add({ key: 'X-OxPHP-Profile', value: pm.environment.get('PROFILE_TOKEN') });

跑完 100 次后,用一行 jq 列出最慢的几次:

bash
curl -sH "Authorization: Bearer $TOK" \ "http://int.app.local:9090/__profiler/runs?limit=200" \ | jq -r '.runs | map(select(.url | startswith("/api/search"))) | sort_by(-.duration_ms) | .[:5] | map("\(.duration_ms)ms \(.run_id) \(.url)") | .[]'

一个为性能分析器供给数据的自定义装饰器

你自己的 #[ProfileDb],它用 metric('db.rows', …) 记录方法返回结果的行数:

php
<?php use OxPHP\Decorator\{AttributeInterface, Context}; use function OxPHP\Profile\metric; #[Attribute(Attribute::TARGET_METHOD)] class ProfileDb implements AttributeInterface { public function before(Context $ctx): void {} public function after(Context $ctx): void { $result = $ctx->getResult(); if (is_array($result)) { metric('db.rows', (float) count($result)); } elseif ($result instanceof PDOStatement) { metric('db.rows', (float) $result->rowCount()); } } } oxphp_register_decorator(ProfileDb::class); class UserRepository { #[ProfileDb] public function findAll(): array { /* ... */ return []; } }

无需额外接线:metric() 会附加到性能分析器此刻正在观测的那个函数的 span 上。装饰器指南介绍了 Context 和 getResult()。

另请参阅

发现错误?报告问题