The Computer Language
Benchmarks Game

binary-trees Go #4 program

source code

/* The Computer Language Benchmarks Game
 * http://benchmarksgame.alioth.debian.org/
 *
 * based on Go program by The Go Authors.
 * based on C program by Kevin Carson
 * flag.Arg hack by Isaac Gouy
 * modified by Jamil Djadala to use goroutines
 * modified by Chai Shushan
 * *reset*
 *
 */

package main

import (
   "flag"
   "fmt"
   "runtime"
   "strconv"
   "sync"
)

var minDepth = 4
var n = 0

func main() {
   runtime.GOMAXPROCS(runtime.NumCPU() * 2)

   flag.Parse()
   if flag.NArg() > 0 {
      n, _ = strconv.Atoi(flag.Arg(0))
   }

   maxDepth := n
   if minDepth+2 > n {
      maxDepth = minDepth + 2
   }
   stretchDepth := maxDepth + 1

   check_l := bottomUpTree(stretchDepth).ItemCheck()
   fmt.Printf("stretch tree of depth %d\t check: %d\n", stretchDepth, check_l)

   longLivedTree := bottomUpTree(maxDepth)

   result_trees := make([]int, maxDepth+1)
   result_check := make([]int, maxDepth+1)

   var wg sync.WaitGroup
   for depth_l := minDepth; depth_l <= maxDepth; depth_l += 2 {
      wg.Add(1)
      go func(depth int) {
         iterations := 1 << uint(maxDepth-depth+minDepth)
         check := 0

         for i := 1; i <= iterations; i++ {
            check += bottomUpTree(depth).ItemCheck()
         }
         result_trees[depth] = iterations
         result_check[depth] = check

         wg.Done()
      }(depth_l)
   }
   wg.Wait()

   for depth := minDepth; depth <= maxDepth; depth += 2 {
      fmt.Printf("%d\t trees of depth %d\t check: %d\n",
         result_trees[depth], depth, result_check[depth],
      )
   }
   fmt.Printf("long lived tree of depth %d\t check: %d\n",
      maxDepth, longLivedTree.ItemCheck(),
   )
}

func bottomUpTree(depth int) *Node {
   if depth <= 0 {
      return &Node{nil, nil}
   }
   return &Node{
      bottomUpTree(depth-1),
      bottomUpTree(depth-1),
   }
}

type Node struct {
   left, right *Node
}

func (self *Node) ItemCheck() int {
   if self.left == nil {
      return 1
   }
   return 1 + self.left.ItemCheck() + self.right.ItemCheck()
}
    

notes, command-line, and program output

NOTES:
64-bit Ubuntu quad core
go version go1.10 linux/amd64


Sat, 17 Feb 2018 18:26:39 GMT

MAKE:
/opt/src/go1.10.linux-amd64/go/bin/go build -o binarytrees.go-4.go_run

0.41s to complete and log all make actions

COMMAND LINE:
./binarytrees.go-4.go_run 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