Created
October 14, 2020 11:10
-
-
Save gollilla/1bceb64798bcb7143e03a2cba7ee6fbd to your computer and use it in GitHub Desktop.
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 | |
//montecarlo | |
const N = 1000000000; | |
/*$counter = 0; | |
for($i=0;$i<N;$i++){ | |
$x = mt_rand() / mt_getrandmax(); | |
$y = mt_rand() / mt_getrandmax(); | |
if(($x**2 + $y**2)**2 < 1) $counter++; | |
} | |
$pi = 4*$counter/N; | |
var_dump($pi);*/ | |
$runtime1 = new \parallel\Runtime; | |
$runtime2 = new \parallel\Runtime; | |
$runtime3 = new \parallel\Runtime; | |
$runtime4 = new \parallel\Runtime; | |
$future1 = $runtime1->run(function(){ | |
$N = 1000000000; | |
$counter = 0; | |
for($i=0;$i<($N/4);$i++){ | |
$x = mt_rand() / mt_getrandmax(); | |
$y = mt_rand() / mt_getrandmax(); | |
if(($x**2 + $y**2)**2 < 1) $counter++; | |
} | |
return $counter; | |
}); | |
$future2 = $runtime2->run(function(){ | |
$counter = 0; | |
$N = 1000000000; | |
for($i=($N/4);$i<($N/4)*2;$i++){ | |
$x = mt_rand() / mt_getrandmax(); | |
$y = mt_rand() / mt_getrandmax(); | |
if(($x**2 + $y**2)**2 < 1) $counter++; | |
} | |
return $counter; | |
}); | |
$future3 = $runtime3->run(function(){ | |
$counter = 0; | |
$N = 1000000000; | |
for($i=($N/4)*2;$i<($N/4)*3;$i++){ | |
$x = mt_rand() / mt_getrandmax(); | |
$y = mt_rand() / mt_getrandmax(); | |
if(($x**2 + $y**2)**2 < 1) $counter++; | |
} | |
return $counter; | |
}); | |
$future4 = $runtime4->run(function(){ | |
$counter = 0; | |
$N = 1000000000; | |
for($i=($N/4)*3;$i<$N;$i++){ | |
$x = mt_rand() / mt_getrandmax(); | |
$y = mt_rand() / mt_getrandmax(); | |
if(($x**2 + $y**2)**2 < 1) $counter++; | |
} | |
return $counter; | |
}); | |
$c = $future1->value() + $future2->value() + $future3->value() + $future4->value(); | |
$pi = 4*$c/N; | |
var_dump($pi); | |
class ParallelFor { | |
public function __construct(Closure $fun, 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; | |
$runtimes = []; | |
for($i=0;$i<$max_parallel;$i++){ | |
$runtime = ParallelFactory::create(); | |
$runtime->run(function() use ($func, $i, $count, $max_parallel){ | |
for($j=($count/$max_parallel)*$i;$j<($count/$max_parallel)*($i+1);$j++){ | |
$func(); | |
} | |
}); | |
} | |
} | |
public function getFunction(){ | |
return $this->func; | |
} | |
public function getMaxParallel(){ | |
return $this->max_parallel; | |
} | |
} | |
class ParallelFactory { | |
public static function create(){ | |
return new \parallel\Runtime; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment