PHP-based cpu speed test. It'll attempt to detect number of cpu cores available and run PI calc.
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 speedTest.php [ITERATIONS] [CONCURRENCY] | |
* | |
* ITERATIONS - (optional) Number of iterations (PI digits) to compute. | |
* Values above 10000 can seriously hog your machine. | |
* CONCURRENCY - (optional) Number of CPU cores to use. If empty, | |
* it's going to attempt to detect the number. | |
* | |
* Press CTRL+C at any time to abort the script. | |
*/ | |
function calcPi($precision) | |
{ | |
$limit = ceil(log($precision) / log(2)) - 1; | |
bcscale($precision + 6); | |
$a = 1; | |
$b = bcdiv(1, bcsqrt(2)); | |
$t = 1 / 4; | |
$p = 1; | |
for ($n = 0; $n < $limit; $n++) { | |
$x = bcdiv(bcadd($a, $b), 2); | |
$y = bcsqrt(bcmul($a, $b)); | |
$t = bcsub($t, bcmul($p, bcpow(bcsub($a, $x), 2))); | |
$a = $x; | |
$b = $y; | |
$p = bcmul(2, $p); | |
} | |
return bcdiv(bcpow(bcadd($a, $b), 2), bcmul(4, $t), $precision); | |
} | |
$iter = !empty($argv[1]) ? (int)$argv[1] : 1000; | |
if(!empty($argv[2])){ | |
$workers = (int)$argv[2]; | |
} else { | |
$workers = (int)shell_exec('nproc'); | |
if($workers) { | |
echo "Detected $workers CPUs.\n"; | |
} else { | |
echo "Cannot detect number of CPUs - using default value of 4.\n"; | |
$workers = 4; | |
} | |
} | |
echo "Iterations: $iter\n"; | |
echo "Workers: $workers\n"; | |
$pids = []; | |
$timeStart = microtime(true); | |
$parent = true; | |
for($x = 0; $x < $workers; $x++ ){ | |
if($pid = pcntl_fork()) { | |
echo " - Worker $x (PID: $pid) running.\n"; | |
$pids[] = $pid; | |
} else { | |
$parent = false; | |
break; // child | |
} | |
} | |
if($parent) { | |
echo "Waiting for workers to finish ... "; | |
foreach($pids as $pid){ | |
pcntl_waitpid($pid, $status); | |
} | |
$duration = microtime(true) - $timeStart; | |
echo "All done!\n"; | |
echo "Time: " . round($duration, 5)."s\n"; | |
} else { | |
calcPi($iter); | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment