プロファイリングの例

組み込みプロファイラーを使う完全な 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); // Profile only the heavy block, even when no trigger was sent. 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; // Optional: tell the frontend that this request was profiled. 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(); // profile only the first file, in full mark('batch.begin', ['path' => $path]); } import_one($path); if ($i === 0) { mark('batch.first_done'); stop(); } $i++; } function import_one(string $path): void { /* ... */ }

2 つの実装を比較する

プロファイル付きのマイクロベンチマークで、素朴な実装とストリーミングの実装を比べます:

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)); // whole file into memory 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]);

両方を実行してから最新の 2 つの実行を取り出し、前後の仮説を検証すると同じように .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 { // If this request is being profiled, turn on extra logging // inside the third-party call. $verbose = is_active(); $gateway = new StripeClient(verbose: $verbose); return $gateway->charge($user->id, $amount); } function oncall_path(Order $order): void { // Profile only VIP users, with no external trigger. 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 Pre-request Script 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() は、その時点でプロファイラーが監視している関数のスパンに付与されます。Context と getResult() についてはデコレーターのガイドで扱います。

関連項目