|
| 1 | +<?php |
| 2 | + |
| 3 | +// This example executes a command within a new container and displays how fast |
| 4 | +// it can receive its output. |
| 5 | +// |
| 6 | +// $ php examples/benchmark-attach.php |
| 7 | +// $ php examples/benchmark-attach.php busybox echo -n hello |
| 8 | +// |
| 9 | +// Expect this to be noticeably faster than the (totally unfair) equivalent: |
| 10 | +// |
| 11 | +// $ docker run -i --rm --log-driver=none busybox dd if=/dev/zero bs=1M count=1000 status=none | dd of=/dev/null |
| 12 | + |
| 13 | +use Clue\React\Docker\Client; |
| 14 | + |
| 15 | +require __DIR__ . '/../vendor/autoload.php'; |
| 16 | + |
| 17 | +if (extension_loaded('xdebug')) { |
| 18 | + echo 'NOTICE: The "xdebug" extension is loaded, this has a major impact on performance.' . PHP_EOL; |
| 19 | +} |
| 20 | + |
| 21 | +$image = 'busybox'; |
| 22 | +$cmd = array('dd', 'if=/dev/zero', 'bs=1M', 'count=1000', 'status=none'); |
| 23 | + |
| 24 | +if (isset($argv[1])) { |
| 25 | + $image = $argv[1]; |
| 26 | + $cmd = array_slice($argv, 2); |
| 27 | +} |
| 28 | + |
| 29 | +$loop = React\EventLoop\Factory::create(); |
| 30 | +$client = new Client($loop); |
| 31 | + |
| 32 | +$client->containerCreate(array( |
| 33 | + 'Image' => $image, |
| 34 | + 'Cmd' => $cmd, |
| 35 | + 'Tty' => false, |
| 36 | + 'HostConfig' => array( |
| 37 | + 'LogConfig' => array( |
| 38 | + 'Type' => 'none' |
| 39 | + ) |
| 40 | + ) |
| 41 | +))->then(function ($container) use ($client, $loop) { |
| 42 | + $stream = $client->containerAttachStream($container['Id'], false, true); |
| 43 | + |
| 44 | + // we're creating the container without a log, so first wait for attach stream before starting |
| 45 | + $loop->addTimer(0.1, function () use ($client, $container) { |
| 46 | + $client->containerStart($container['Id'])->then(null, 'printf'); |
| 47 | + }); |
| 48 | + |
| 49 | + $start = microtime(true); |
| 50 | + $bytes = 0; |
| 51 | + $stream->on('data', function ($chunk) use (&$bytes) { |
| 52 | + $bytes += strlen($chunk); |
| 53 | + }); |
| 54 | + |
| 55 | + $stream->on('error', 'printf'); |
| 56 | + |
| 57 | + // show stats when stream ends |
| 58 | + $stream->on('close', function () use ($client, &$bytes, $start, $container) { |
| 59 | + $time = microtime(true) - $start; |
| 60 | + $client->containerRemove($container['Id'])->then(null, 'printf'); |
| 61 | + |
| 62 | + echo 'Received ' . $bytes . ' bytes in ' . round($time, 1) . 's => ' . round($bytes / $time / 1000000, 1) . ' MB/s' . PHP_EOL; |
| 63 | + }); |
| 64 | +}, 'printf'); |
| 65 | + |
| 66 | +$loop->run(); |
0 commit comments