Exemples de profilage
Des scénarios PHP complets pour le profileur intégré. Le guide de profilage explique les déclencheurs et le SDK qu'ils utilisent, et la Référence du profileur les réglages et les fichiers.
Chaque script peut être déposé dans www/public/ de la configuration du démarrage rapide du guide, puis interrogé avec curl.
Contrôleur simple avec contrôle manuel
<?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');
}Invocation :
curl -H "X-OxPHP-Profile: dev-secret" 'http://localhost/report.php?user_id=42'Classe de service avec attributs
<?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 { /* ... */ }
}Job par lot : profiler uniquement la première itération sur N
<?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 { /* ... */ }Comparer deux implémentations
Un micro-benchmark avec profils, version naïve contre version en streaming :
<?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]);Lancez les deux, puis prenez les deux runs les plus récents et comparez leurs fichiers .collapsed comme dans Valider une hypothèse avant/après :
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'Profilage conditionnel dans du code de production
Le cas classique : une fonction n'est lente que pour certains utilisateurs.
<?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();
}
}Un test de fumée qui se profile lui-même
Un script qui active le profilage depuis PHP et indique si le SDK se comporte comme prévu. Aucun déclencheur n'est nécessaire, mais le profileur doit être activé (PROFILER_ENABLED=true), sinon start() ne fait rien. Appelez-le sans l'en-tête, et sur un serveur où l'échantillonnage ne le sélectionnera pas.
<?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);Trouver un point chaud à partir d'une série de requêtes Postman
Le scénario : /api/search est parfois lent, pas toujours. Profilez chaque requête d'un run Postman :
// Postman Pre-request Script
pm.request.headers.add({
key: 'X-OxPHP-Profile',
value: pm.environment.get('PROFILE_TOKEN')
});Après 100 runs, un one-liner jq liste les pires :
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)")
| .[]'Un décorateur personnalisé qui alimente le profileur
Votre propre #[ProfileDb], qui enregistre avec metric('db.rows', …) le nombre de lignes de ce que renvoie une méthode :
<?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 []; }
}Aucun câblage supplémentaire n'est nécessaire : metric() s'attache au span de la fonction que le profileur surveille à cet instant. Le guide Décorateurs décrit Context et getResult().
Voir aussi
- Profilage du code PHP — le guide, avec les déclencheurs, le SDK PHP et les workflows
- Référence du profileur — réglages, exports et routes
- Décorateurs — écrire et enregistrer vos propres attributs