binary-trees PHP #3 program
source code
<?php
/* The Computer Language Benchmarks Game
https://salsa.debian.org/benchmarksgame-team/benchmarksgame/
contributed by Peter Baltruschat
modified by Levi Cameron
*reset*
*/
function bottomUpTree($depth)
{
if (!$depth) return array(null,null);
$depth--;
return array(
bottomUpTree($depth),
bottomUpTree($depth));
}
function itemCheck($treeNode) {
return 1
+ ($treeNode[0][0] === null ? 1 : itemCheck($treeNode[0]))
+ ($treeNode[1][0] === null ? 1 : itemCheck($treeNode[1]));
}
$minDepth = 4;
$n = ($argc == 2) ? $argv[1] : 1;
$maxDepth = max($minDepth + 2, $n);
$stretchDepth = $maxDepth + 1;
$stretchTree = bottomUpTree($stretchDepth);
printf("stretch tree of depth %d\t check: %d\n",
$stretchDepth, itemCheck($stretchTree));
unset($stretchTree);
$longLivedTree = bottomUpTree($maxDepth);
$iterations = 1 << ($maxDepth);
do
{
$check = 0;
for($i = 1; $i <= $iterations; ++$i)
{
$t = bottomUpTree($minDepth);
$check += itemCheck($t);
unset($t);
}
printf("%d\t trees of depth %d\t check: %d\n", $iterations, $minDepth, $check);
$minDepth += 2;
$iterations >>= 2;
}
while($minDepth <= $maxDepth);
printf("long lived tree of depth %d\t check: %d\n",
$maxDepth, itemCheck($longLivedTree));
?>
notes, command-line, and program output
NOTES:
64-bit Ubuntu quad core
PHP 7.4.5 (cli) (built: May 11 2020 13:25:48) ( NTS )
Copyright (c) The PHP Group
Zend Engine v3.4.0, Copyright (c) Zend Technologies
Mon, 11 May 2020 20:43:12 GMT
COMMAND LINE:
/opt/src/php-7.4.5/bin/php -n -d memory_limit=4096M binarytrees.php-3.php 21
PROGRAM OUTPUT:
stretch tree of depth 22 check: 8388607
2097152 trees of depth 4 check: 65011712
524288 trees of depth 6 check: 66584576
131072 trees of depth 8 check: 66977792
32768 trees of depth 10 check: 67076096
8192 trees of depth 12 check: 67100672
2048 trees of depth 14 check: 67106816
512 trees of depth 16 check: 67108352
128 trees of depth 18 check: 67108736
32 trees of depth 20 check: 67108832
long lived tree of depth 21 check: 4194303