|
| 1 | +<?php |
| 2 | + |
| 3 | +use React\EventLoop\Factory; |
| 4 | +use React\ChildProcess\Process; |
| 5 | +use React\Stream\Stream; |
| 6 | + |
| 7 | +require __DIR__ . '/../vendor/autoload.php'; |
| 8 | + |
| 9 | +$loop = Factory::create(); |
| 10 | + |
| 11 | +$info = new React\Stream\Stream(STDERR, $loop); |
| 12 | +$info->pause(); |
| 13 | +$info->write('Pipes data through process STDIN and reads STDOUT again' . PHP_EOL); |
| 14 | +if (extension_loaded('xdebug')) { |
| 15 | + $info->write('NOTICE: The "xdebug" extension is loaded, this has a major impact on performance.' . PHP_EOL); |
| 16 | +} |
| 17 | + |
| 18 | +$process = new Process('cat'); |
| 19 | +$process->start($loop); |
| 20 | +$start = microtime(true); |
| 21 | + |
| 22 | +$chunks = 0; |
| 23 | +$bytes = 0; |
| 24 | +$process->stdout->on('data', function ($chunk) use (&$chunks, &$bytes) { |
| 25 | + ++$chunks; |
| 26 | + $bytes += strlen($chunk); |
| 27 | +}); |
| 28 | + |
| 29 | +// 10000 * 100 KB => 1 GB |
| 30 | +$i = 10000; |
| 31 | +$chunk = str_repeat("\0", 100 * 1000); |
| 32 | +$write = function () use ($chunk, $process, &$i, &$write) { |
| 33 | + do { |
| 34 | + --$i; |
| 35 | + $continue = $process->stdin->write($chunk); |
| 36 | + } while ($i && $continue); |
| 37 | + |
| 38 | + if ($i > 0) { |
| 39 | + // buffer full => wait for drain to continue |
| 40 | + $process->stdin->once('drain', $write); |
| 41 | + } else { |
| 42 | + $process->stdin->end(); |
| 43 | + } |
| 44 | +}; |
| 45 | +$write(); |
| 46 | + |
| 47 | +// print stream position once process exits |
| 48 | +$process->on('exit', function () use (&$chunks, &$bytes, $start, $info) { |
| 49 | + $t = microtime(true) - $start; |
| 50 | + |
| 51 | + $info->write('read ' . $chunks . ' chunks with ' . $bytes . ' byte(s) in ' . round($t, 3) . ' second(s) => ' . round($bytes / 1024 / 1024 / $t, 1) . ' MiB/s' . PHP_EOL); |
| 52 | + $info->write('peak memory usage of ' . round(memory_get_peak_usage(true) / 1024 / 1024, 1) . ' MiB' . PHP_EOL); |
| 53 | +}); |
| 54 | + |
| 55 | +// report any other output/errors |
| 56 | +$process->stdout->on('error', 'printf'); |
| 57 | +$process->stderr->on('data', 'printf'); |
| 58 | +$process->stdout->on('error', 'printf'); |
| 59 | + |
| 60 | +$loop->run(); |
0 commit comments