|
| 1 | +<?php |
| 2 | + |
| 3 | +// This benchmarking example reads a compressed file and displays how fast |
| 4 | +// it can be decompressed. |
| 5 | +// |
| 6 | +// Before starting the benchmark, you have to create a (dummy) compressed file first, such as: |
| 7 | +// |
| 8 | +// $ dd if=/dev/zero bs=1M count=1k status=progress | gzip > null.gz |
| 9 | +// |
| 10 | +// You can run the benchmark like this: |
| 11 | +// |
| 12 | +// $ php examples/92-benchmark-decompress.php null.gz |
| 13 | +// |
| 14 | +// Expect this to be slightly faster than the (totally unfair) equivalent: |
| 15 | +// |
| 16 | +// $ gunzip < null.gz | dd of=/dev/null status=progress |
| 17 | +// |
| 18 | +// Expect this to be somewhat faster than: |
| 19 | +// |
| 20 | +// $ php examples/gunzip.php < null.gz | dd of=/dev/zero status=progress |
| 21 | + |
| 22 | +require __DIR__ . '/../vendor/autoload.php'; |
| 23 | + |
| 24 | +if (DIRECTORY_SEPARATOR === '\\') { |
| 25 | + fwrite(STDERR, 'Non-blocking console I/O not supported on Windows' . PHP_EOL); |
| 26 | + exit(1); |
| 27 | +} |
| 28 | + |
| 29 | +if (!defined('ZLIB_ENCODING_GZIP')) { |
| 30 | + fwrite(STDERR, 'Requires PHP 5.4+ with ext-zlib enabled' . PHP_EOL); |
| 31 | + exit(1); |
| 32 | +} |
| 33 | + |
| 34 | +if ($argc !== 2) { |
| 35 | + fwrite(STDERR, 'No archive given, requires single argument' . PHP_EOL); |
| 36 | + exit(1); |
| 37 | +} |
| 38 | + |
| 39 | +if (extension_loaded('xdebug')) { |
| 40 | + echo 'NOTICE: The "xdebug" extension is loaded, this has a major impact on performance.' . PHP_EOL; |
| 41 | +} |
| 42 | + |
| 43 | +$loop = React\EventLoop\Factory::create(); |
| 44 | + |
| 45 | +$in = new React\Stream\ReadableResourceStream(fopen($argv[1], 'r'), $loop); |
| 46 | +$stream = new Clue\React\Zlib\Decompressor(ZLIB_ENCODING_GZIP); |
| 47 | +$in->pipe($stream); |
| 48 | + |
| 49 | +$bytes = 0; |
| 50 | +$stream->on('data', function ($chunk) use (&$bytes) { |
| 51 | + $bytes += strlen($chunk); |
| 52 | +}); |
| 53 | + |
| 54 | +$stream->on('error', 'printf'); |
| 55 | + |
| 56 | +//report progress periodically |
| 57 | +$timer = $loop->addPeriodicTimer(0.2, function () use (&$bytes) { |
| 58 | + echo "\rDecompressed $bytes bytes…"; |
| 59 | +}); |
| 60 | + |
| 61 | +// show stats when stream ends |
| 62 | +$start = microtime(true); |
| 63 | +$stream->on('close', function () use (&$bytes, $start, $loop, $timer) { |
| 64 | + $time = microtime(true) - $start; |
| 65 | + $loop->cancelTimer($timer); |
| 66 | + |
| 67 | + echo "\rDecompressed $bytes bytes in " . round($time, 1) . 's => ' . round($bytes / $time / 1000000, 1) . ' MB/s' . PHP_EOL; |
| 68 | +}); |
| 69 | + |
| 70 | +$loop->run(); |
0 commit comments