Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- <?php
- declare(strict_types = 1);
- /** @noinspection AutoloadingIssuesInspection */
- class BenchmarkCase
- {
- public static $maxNameLength;
- public $callable;
- public $iterations = 0;
- public $name;
- public $timing = 0;
- public static function create(string $name, callable $callable): self
- {
- $self = new self;
- $self->name = $name;
- $self->callable = $callable;
- self::$maxNameLength = max(self::$maxNameLength, strlen($name));
- return $self;
- }
- public static function printResults(float $initialMs, array $cases): void
- {
- $durationMs = microtime(true) - $initialMs;
- printf("\r");
- usort($cases, static function (BenchmarkCase $a, BenchmarkCase $b) {
- return $a->timing <=> $b->timing;
- });
- $caseFirst = $cases[0]->timing;
- /** @var BenchmarkCase $case */
- foreach ($cases as $case) {
- printf("Case %s duration of %.6fs (avg. each %.8fs) +%.2f%%\n",
- str_pad($case->name, self::$maxNameLength, ' '),
- $case->timing,
- bcdiv((string) $case->timing, (string) $case->iterations, 8),
- (100 / $caseFirst * $case->timing) - 100);
- }
- printf("\nTotal duration: %.6fs",
- $durationMs);
- }
- }
- set_error_handler(static function ($severity, $message) {
- throw new ErrorException($message, 0, $severity);
- });
- $cases = [
- BenchmarkCase::create('array_merge() inside looping', static function () {
- $arr = [];
- for ($i = 0; $i < 100; $i++) {
- $arr = array_merge($arr, [ $i, $i ]);
- }
- return $arr;
- }),
- BenchmarkCase::create('array_merge() after looping', static function () {
- $arrArr = [];
- for ($i = 0; $i < 100; $i++) {
- $arrArr[] = [ $i, $i ];
- }
- return array_merge(... $arrArr);
- }),
- BenchmarkCase::create('array_push() inside looping', static function () {
- $arr = [];
- for ($i = 0; $i < 100; $i++) {
- array_push($arr, $i, $i);
- }
- return $arr;
- }),
- ];
- const BENCHMARK_DURATION_MS = 90000;
- const CYCLES_ITERATION = 100;
- $initialMs = microtime(true);
- $stopTiming = $initialMs + BENCHMARK_DURATION_MS / 1000;
- while (($currentTiming = microtime(true)) < $stopTiming) {
- /** @noinspection NonSecureShuffleUsageInspection */
- shuffle($cases);
- printf("Processing: %.2f%%\r", 100 / ($stopTiming - $initialMs) * ($currentTiming - $initialMs));
- /** @var BenchmarkCase $case */
- foreach ($cases as $case) {
- $startMs = microtime(true);
- for ($j = 0; $j < CYCLES_ITERATION; $j++) {
- call_user_func($case->callable);
- }
- $case->iterations += CYCLES_ITERATION;
- $case->timing += microtime(true) - $startMs;
- }
- }
- BenchmarkCase::printResults($initialMs, $cases);
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement