-
-
Save krakjoe/254897be71d23b5d5ac2d436f52e8d7d to your computer and use it in GitHub Desktop.
perf.parallel vs perf.zend
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
krakjoe@fiji:/opt/src/parallel$ php parallel.php 0 | |
Finished without threads in 4.33 seconds | |
krakjoe@fiji:/opt/src/parallel$ php parallel.php 4 | |
Finished with 4 threads in 1.21 seconds | |
krakjoe@fiji:/opt/src/parallel$ php parallel.php 8 | |
Finished with 8 threads in 0.66 seconds |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/* | |
usage: php parallel.php [workers=8] | |
*/ | |
class AutoConfiguringParallelPool { | |
public function __construct(int $workers, string $bootstrap = null, array $configuration = []) { | |
for ($i = 0; $i < $workers; $i++) { | |
if ($bootstrap && $configuration) { | |
$this->workers[$i] = new \parallel\Runtime( | |
$bootstrap, | |
\array_merge($configuration, \ini_get_all())); | |
} else if ($bootstrap) { | |
$this->workers[$i] = new \parallel\Runtime($bootstrap, \ini_get_all()); | |
} else { | |
$this->workers[$i] = new \parallel\Runtime(\ini_get_all()); | |
} | |
} | |
} | |
public function submit(Closure $closure, array $argv = []) : ?\parallel\Future { | |
if ($this->worker >= count($this->workers)) { | |
$this->worker = 0; | |
} | |
return $this->workers[$this->worker++]->run($closure, $argv); | |
} | |
public function shutdown(bool $finish = true) { | |
foreach ($this->workers as $worker) { | |
$finish ? | |
$worker->close() : | |
$worker->kill(); | |
} | |
} | |
private $workers = []; | |
private $worker = 0; | |
} | |
$workers = @$argv[1] ?? 8; | |
if ($workers) | |
$pool = new AutoConfiguringParallelPool($workers); | |
$start = microtime(true); | |
while (@$i++<100000) { | |
if (!$workers) { | |
(function(){ | |
for ($i = 0; $i < 1000; $i++) | |
$result[] = mt_rand(1,1000); | |
})(); | |
} else { | |
$pool->submit(function(){ | |
for ($i = 0; $i < 1000; $i++) | |
$result[] = mt_rand(1,1000); | |
}); | |
} | |
} | |
if ($workers) | |
$pool->shutdown(); | |
printf("Finished %s threads in %.2f seconds\n", | |
$workers ? "with {$workers}" : "without", | |
microtime(true) - $start); | |
?> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment