Lab 14: Performance Profiling
Overview
Step 1: Benchmarking Framework
<?php
class Profiler {
private array $timings = [];
private array $memory = [];
public function measure(string $name, callable $fn, int $iterations = 1): mixed {
$memBefore = memory_get_usage(true);
$timings = [];
$result = null;
// Warmup
$fn();
for ($i = 0; $i < $iterations; $i++) {
$start = hrtime(true);
$result = $fn();
$timings[] = hrtime(true) - $start;
}
sort($timings);
$this->timings[$name] = [
'min' => min($timings) / 1_000_000,
'max' => max($timings) / 1_000_000,
'avg' => array_sum($timings) / count($timings) / 1_000_000,
'median' => $timings[(int)(count($timings) / 2)] / 1_000_000,
'p95' => $timings[(int)(count($timings) * 0.95)] / 1_000_000,
];
$this->memory[$name] = (memory_get_usage(true) - $memBefore) / 1024;
return $result;
}
public function report(): void {
printf("\n%-35s %8s %8s %8s %8s %8s %8s\n",
'Benchmark', 'Min(ms)', 'Avg(ms)', 'Median', 'P95', 'Max', 'Memory');
echo str_repeat('─', 95) . "\n";
foreach ($this->timings as $name => $t) {
printf("%-35s %8.3f %8.3f %8.3f %8.3f %8.3f %6.1fKB\n",
$name,
$t['min'], $t['avg'], $t['median'], $t['p95'], $t['max'],
$this->memory[$name]
);
}
}
public function compare(string $baseline, string $candidate): void {
$b = $this->timings[$baseline]['avg'] ?? 0;
$c = $this->timings[$candidate]['avg'] ?? 0;
$ratio = $b > 0 ? $b / $c : 0;
$diff = round(($c - $b) / $b * 100, 1);
$symbol = $c < $b ? '🚀 faster' : '🐌 slower';
printf(" %s vs %s: %+.1f%% (%s)\n", $candidate, $baseline, -$diff, $symbol);
}
}
$p = new Profiler();
echo "Profiler ready. hrtime() precision: " . hrtime(true) . " ns\n";Step 2: Array Iteration Benchmarks
Step 3: String Operation Benchmarks
Step 4: OPcache Configuration Analysis
Step 5: Realpath Cache & File System Performance
Step 6: PHP Preloading (opcache.preload)
Step 7: Memory Profiling
Step 8: Capstone — Comprehensive Performance Suite
Summary
Technique
Method
Expected Impact
Last updated
