Przykłady profilowania
Kompletne scenariusze PHP dla wbudowanego profilera. Przewodnik po profilowaniu wyjaśnia wyzwalacze i SDK, z których te scenariusze korzystają, a Dokumentacja profilera ustawienia i pliki.
Każdy skrypt możesz wrzucić do www/public/ konfiguracji ze szybkiego startu w przewodniku i wywołać curl-em.
Prosty kontroler z ręcznym sterowaniem
<?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');
}Wywołanie:
curl -H "X-OxPHP-Profile: dev-secret" 'http://localhost/report.php?user_id=42'Klasa serwisu z atrybutami
<?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 { /* ... */ }
}Zadanie wsadowe: profiluj tylko pierwszą z N iteracji
<?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 { /* ... */ }Porównanie dwóch implementacji
Mikrobenchmark z profilami: wersja naiwna przeciwko strumieniowej:
<?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]);Uruchom obie, a potem weź dwa najnowsze przebiegi i porównaj ich pliki .collapsed jak w sekcji Zweryfikuj hipotezę „przed i po":
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'Warunkowe profilowanie w kodzie produkcyjnym
Klasyczny przypadek: funkcja jest wolna tylko dla niektórych użytkowników.
<?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();
}
}Test dymny, który sam się profiluje
Skrypt, który włącza profilowanie z PHP i raportuje, czy SDK działa poprawnie. Wyzwalacz nie jest potrzebny, ale profiler musi być włączony (PROFILER_ENABLED=true), inaczej start() nic nie robi. Wywołaj go bez nagłówka i na serwerze, na którym próbkowanie go nie wybierze.
<?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);Znajdowanie hotspotu z serii żądań Postmana
Scenariusz: /api/search bywa wolny, ale nie zawsze. Profiluj każde żądanie z uruchomienia kolekcji w Postmanie:
// Postman Pre-request Script
pm.request.headers.add({
key: 'X-OxPHP-Profile',
value: pm.environment.get('PROFILE_TOKEN')
});Po 100 przebiegach jednolinijkowiec jq wypisuje najgorsze z nich:
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)")
| .[]'Własny dekorator zasilający profiler
Twój własny #[ProfileDb], który przez metric('db.rows', …) zapisuje liczbę wierszy w tym, co zwraca metoda:
<?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 []; }
}Nie trzeba nic dodatkowo podłączać: metric() dołącza się do spanu funkcji, którą profiler w tej chwili obserwuje. Context i getResult() opisuje przewodnik Dekoratory.
Zobacz też
- Profilowanie kodu PHP — przewodnik: wyzwalacze, PHP SDK i przepływy pracy
- Dokumentacja profilera — ustawienia, eksporty i trasy
- Dekoratory — pisanie i rejestrowanie własnych atrybutów