The Computer Language
24.11 Benchmarks Game

binary-trees PHP #8 program

source code

<? /* The Computer Language Benchmarks Game
   https://salsa.debian.org/benchmarksgame-team/benchmarksgame/
   
   contributed by Isaac Gouy   
*/
       
final class Tree {
   var $left, $right;

   public function __construct($left, $right) {
      $this->left = $left;
      $this->right = $right;
   }    
      
   static function with($depth) {
      return $depth == 0
         ? new Tree(null, null)
         : new Tree( Tree::with($depth-1), Tree::with($depth-1));
   }      

   function nodeCount() {
      return is_null($this->left)
         ? 1 
         : 1 + $this->left->nodeCount() + $this->right->nodeCount();
   }  
   
   function clear() {
      if ($this->left != null) {
         $this->left->clear(); 
         unset( $this->left );
         $this->right->clear();
         unset( $this->right );         
      }
   }    
} 

const MIN_DEPTH = 4;
   
function main ($n) { 
   define("MAX_DEPTH", MIN_DEPTH + 2 > $n ? MIN_DEPTH + 2 : $n);  
   define("STRETCH_DEPTH", MAX_DEPTH + 1);  
     
   stretch(STRETCH_DEPTH);      
   $longLivedTree = Tree::with(MAX_DEPTH);   
   
   for ($depth = MIN_DEPTH; $depth < STRETCH_DEPTH; $depth += 2){
      $iterations = 1 << (MAX_DEPTH - $depth + MIN_DEPTH);
      $sum = 0; 

      for ($i = 1; $i <= $iterations; $i++){
         $sum += count_($depth);
      } 
      printf("%d\t trees of depth %d\t check: %d\n",
            $iterations, $depth, $sum);      
   }      
   printf("long lived tree of depth %d\t check: %d\n",
         MAX_DEPTH, $longLivedTree->nodeCount());   
}

function stretch($depth) {        
   printf("stretch tree of depth %d\t check: %d\n", $depth, count_($depth));     
}

function count_($depth){
   $t = Tree::with($depth);         
   $c = $t->nodeCount();
   $t->clear(); 
   return $c;
}

$n = $argc > 1 ? $argv[1] : 10;
main($n);
?>
    

notes, command-line, and program output

NOTES:
64-bit Ubuntu quad core
PHP 8.4.1 (cli)
(built: Nov 22 2024 14:22:47) (NTS)
Copyright (c) The PHP Group
Zend Engine v4.4.1,
with Zend OPcache v8.4.1,
Copyright (c) Zend Technologies


 Sat, 23 Nov 2024 03:16:11 GMT

COMMAND LINE:
 /opt/src/php-8.4.1/bin/php -dzend_extension=/opt/src/php-8.4.1/lib/php/extensions/no-debug-non-zts-20240924/opcache.so -dopcache.enable_cli=1 -dopcache.jit_buffer_size=64M -n -d memory_limit=4096M binarytrees.php-8.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