Skip to content

Instantly share code, notes, and snippets.

@Thinkscape
Last active August 29, 2015 13:56
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save Thinkscape/8998740 to your computer and use it in GitHub Desktop.
PHP-based cpu speed test. It'll attempt to detect number of cpu cores available and run PI calc.
<?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