Skip to content

Instantly share code, notes, and snippets.

@gollilla
Last active August 30, 2023 14:46
Show Gist options
  • Save gollilla/7004948ba286e4954ec9c1167db31f8d to your computer and use it in GitHub Desktop.
Save gollilla/7004948ba286e4954ec9c1167db31f8d to your computer and use it in GitHub Desktop.
Parallelを使ってモンテカルロを並列計算
<?php
const N = 100000000;
$para_count = 12;
$parallel = new ParallelFor(function(int $c){
$x = mt_rand() / mt_getrandmax();
$y = mt_rand() / mt_getrandmax();
if(($x**2 + $y**2)**2 < 1) $c++;
return $c;
}, N, $para_count);
$c = 0;
for($i=0;$i<$para_count;$i++){
$c += $parallel->getFutures()[$i]->value();
}
$pi = 4*$c/N;
var_dump($pi);
class ParallelFor {
public function __construct(Closure $func, int $count, int $max_parallel){
$this->func = $func;
if($count < $max_parallel){
echo 'count < max_parallel', PHP_EOL;
return;
}
$this->count = $count;
$this->max_parallel = $max_parallel;
$futures = [];
for($i=0;$i<$max_parallel;$i++){
$runtime = ParallelFactory::create();
$futures[] = $runtime->run(function() use ($func, $i, $count, $max_parallel){
$c = 0;
for($j=($count/$max_parallel)*$i;$j<($count/$max_parallel)*($i+1);$j++){
$c = ($func)($c);
}
return $c;
});
}
$this->futures = $futures;
}
public function getFunction(){
return $this->func;
}
public function getFutures(){
return $this->futures;
}
public function getMaxParallel(){
return $this->max_parallel;
}
}
class ParallelFactory {
public static function create(){
return new \parallel\Runtime;
}
}
@gollilla
Copy link
Author

汎用性のある書き方を見つけたい

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment