PHP高精度计时器与性能基准性能测试需要高精度计时。PHP的microtime和hrtime可以精确到微秒和纳秒。今天说说PHP中计时和性能基准测试。microtime的使用。php$start microtime(true);usleep(150000);$end microtime(true);echo 耗时: . round(($end - $start) * 1000, 3) . ms\n;// hrtime更高精度PHP 7.3$start hrtime(true);usleep(150000);$end hrtime(true);echo 耗时: . round(($end - $start) / 1e6, 3) . ms\n;?性能基准测试工具。phpclass Benchmark{private array $results [];public function add(string $name, callable $fn, int $iterations 1000): void{// 预热$fn();$start hrtime(true);for ($i 0; $i $iterations; $i) {$fn();}$end hrtime(true);$totalNs $end - $start;$avgNs $totalNs / $iterations;$this-results[] [name $name,iterations $iterations,total_ms round($totalNs / 1e6, 3),avg_us round($avgNs / 1000, 3),];}public function report(): string{$report 基准测试结果\n . str_repeat(-, 60) . \n;$report . sprintf(%-25s %-15s %-15s\n, 测试, 总耗时(ms), 平均(us));$report . str_repeat(-, 60) . \n;foreach ($this-results as $r) {$report . sprintf(%-25s %-15s %-15s\n, $r[name], $r[total_ms], $r[avg_us]);}return $report;}}$bench new Benchmark();$bench-add(array_push, function () {$arr [];for ($i 0; $i 100; $i) array_push($arr, $i);}, 1000);$bench-add(arr[], function () {$arr [];for ($i 0; $i 100; $i) $arr[] $i;}, 1000);$bench-add(implode, function () {implode(,, range(0, 99));}, 1000);echo $bench-report();?性能对比测试。phpfunction benchmarkComparison(): void{$data range(1, 10000);$target 9999;// in_array$start hrtime(true);for ($i 0; $i 100; $i) in_array($target, $data);echo in_array: . round((hrtime(true) - $start) / 1e6, 2) . ms\n;// array_flip isset$flipped array_flip($data);$start hrtime(true);for ($i 0; $i 100; $i) isset($flipped[$target]);echo isset: . round((hrtime(true) - $start) / 1e6, 2) . ms\n;}benchmarkComparison();?时间单位转换。phpfunction formatDuration(float $seconds): string{if ($seconds 0.001) return round($seconds * 1000000, 2) . μs;if ($seconds 1) return round($seconds * 1000, 2) . ms;if ($seconds 60) return round($seconds, 2) . s;return floor($seconds / 60) . m . round($seconds % 60, 2) . s;}echo formatDuration(0.00015) . \n;echo formatDuration(0.5) . \n;echo formatDuration(125.5) . \n;?PHP的高精度计时器在性能测试中很重要。microtime精确到微秒hrtime精确到纳秒。基准测试要预热让OPcache生效多次测试取平均值。对比测试选择合适的数据结构。