Примеры профилирования

Готовые 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 { /* ... */ }

Сравнить две реализации

Микро-бенчмарк с профилями, наивная реализация против потоковой:

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]);

Запустите обе, затем возьмите два последних прогона и сравните их файлы .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() описаны в руководстве Декораторы.

См. также

Нашли ошибку? Сообщите