Skip to content

Instantly share code, notes, and snippets.

@JanTvrdik
Last active February 1, 2017 00:43
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save JanTvrdik/5897869 to your computer and use it in GitHub Desktop.
Save JanTvrdik/5897869 to your computer and use it in GitHub Desktop.
<?php
class Buffer
{
public $data = '';
public $end = FALSE;
}
class Loop
{
public $readStreams = [];
public $writeStreams = [];
public $buffers = []; // streamId => buffer
public function run()
{
while (count($this->readStreams) + count($this->writeStreams)) {
$r = $this->readStreams;
$w = $this->writeStreams;
$e = NULL;
if (stream_select($r, $w, $e, 0) > 0) {
foreach ((array) $r as $stream) {
$buffer = $this->buffers[(int) $stream];
$buffer->data .= fread($stream, 1024);
if (feof($stream)) {
unset($this->readStreams[(int) $stream]);
$buffer->end = TRUE;
}
}
foreach ((array) $w as $stream) {
$buffer = $this->buffers[(int) $stream];
if ($buffer->data) {
fwrite($stream, $buffer->data);
$buffer->data = '';
if ($buffer->end) {
unset($this->writeStreams[(int) $stream]);
}
}
}
}
}
}
}
// =====================================================================================================================
function downloadAsync($files)
{
$loop = new Loop();
foreach ($files as $file => $url) {
$readStream = fopen($url, 'rb');
$writeStream = fopen($file, 'wb');
$buffer = new Buffer();
stream_set_blocking($readStream, 0);
stream_set_blocking($writeStream, 0);
$loop->readStreams[(int) $readStream] = $readStream;
$loop->writeStreams[(int) $writeStream] = $writeStream;
$loop->buffers[(int) $readStream] = $buffer;
$loop->buffers[(int) $writeStream] = $buffer;
}
$loop->run();
}
function downloadSync($files)
{
foreach ($files as $file => $url) {
copy($url, $file);
}
}
// =====================================================================================================================
$files = array(
'node-v0.6.18.tar.gz' => 'http://nodejs.org/dist/v0.6.18/node-v0.6.18.tar.gz',
'php-5.5.0.tar.gz' => 'http://cz1.php.net/get/php-5.5.0.tar.xz/from/this/mirror',
'ruby-2.0.0-p195-i386-mingw32.7z' => 'http://rubyforge.org/frs/download.php/76957/ruby-2.0.0-p195-i386-mingw32.7z',
);
$start = microtime(TRUE);
downloadAsync($files);
$end = microtime(TRUE);
printf("Async download time: %.3f seconds\n", $end - $start);
$start = microtime(TRUE);
downloadSync($files);
$end = microtime(TRUE);
printf("Sync download time: %.3f seconds\n", $end - $start);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment