1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84
| <?php class PerformanceBenchmark { private $results = []; public function benchmark($name, callable $callback, $iterations = 1000) { for ($i = 0; $i < 10; $i++) { $callback(); } gc_collect_cycles(); $startTime = microtime(true); $startMemory = memory_get_usage(); for ($i = 0; $i < $iterations; $i++) { $callback(); } $endTime = microtime(true); $endMemory = memory_get_usage(); $this->results[$name] = [ 'time' => ($endTime - $startTime) * 1000, 'memory' => $endMemory - $startMemory, 'iterations' => $iterations ]; return $this; } public function getResults() { return $this->results; } public function printResults() { echo "=== 性能基准测试结果 ===\n"; foreach ($this->results as $name => $result) { printf("%-30s: %8.2fms, %8s bytes\n", $name, $result['time'], number_format($result['memory'])); } } public function compare($test1, $test2) { if (!isset($this->results[$test1]) || !isset($this->results[$test2])) { throw new InvalidArgumentException("测试结果不存在"); } $result1 = $this->results[$test1]; $result2 = $this->results[$test2]; $timeImprovement = ($result1['time'] - $result2['time']) / $result1['time'] * 100; $memoryImprovement = ($result1['memory'] - $result2['memory']) / abs($result1['memory']) * 100; echo "=== 性能对比: $test1 vs $test2 ===\n"; printf("时间改进: %+.2f%%\n", $timeImprovement); printf("内存改进: %+.2f%%\n", $memoryImprovement); } }
$benchmark = new PerformanceBenchmark();
$benchmark->benchmark('数组创建', function() { $arr = range(1, 1000); return $arr; }, 1000);
$benchmark->benchmark('数组过滤', function() { $arr = range(1, 1000); return array_filter($arr, fn($x) => $x % 2 === 0); }, 1000);
$benchmark->benchmark('数组映射', function() { $arr = range(1, 1000); return array_map(fn($x) => $x * 2, $arr); }, 1000);
$benchmark->printResults(); ?>
|