github.com/undoio/delve@v1.9.0/_fixtures/binarytrees.go (about) 1 /* The Computer Language Benchmarks Game 2 * http://benchmarksgame.alioth.debian.org/ 3 * 4 * based on Go program by The Go Authors. 5 * based on C program by Kevin Carson 6 * flag.Arg hack by Isaac Gouy 7 * modified by Jamil Djadala to use goroutines 8 * modified by Chai Shushan 9 * 10 */ 11 12 package main 13 14 import ( 15 "flag" 16 "fmt" 17 "runtime" 18 "strconv" 19 "sync" 20 ) 21 22 var minDepth = 4 23 var n = 20 24 25 func main() { 26 runtime.GOMAXPROCS(runtime.NumCPU() * 2) 27 28 flag.Parse() 29 if flag.NArg() > 0 { 30 n, _ = strconv.Atoi(flag.Arg(0)) 31 } 32 33 maxDepth := n 34 if minDepth+2 > n { 35 maxDepth = minDepth + 2 36 } 37 stretchDepth := maxDepth + 1 38 39 check_l := bottomUpTree(0, stretchDepth).ItemCheck() 40 fmt.Printf("stretch tree of depth %d\t check: %d\n", stretchDepth, check_l) 41 42 longLivedTree := bottomUpTree(0, maxDepth) 43 44 result_trees := make([]int, maxDepth+1) 45 result_check := make([]int, maxDepth+1) 46 47 var wg sync.WaitGroup 48 for depth_l := minDepth; depth_l <= maxDepth; depth_l += 2 { 49 wg.Add(1) 50 go func(depth int) { 51 iterations := 1 << uint(maxDepth-depth+minDepth) 52 check := 0 53 54 for i := 1; i <= iterations; i++ { 55 check += bottomUpTree(i, depth).ItemCheck() 56 check += bottomUpTree(-i, depth).ItemCheck() 57 } 58 result_trees[depth] = iterations * 2 59 result_check[depth] = check 60 61 wg.Done() 62 }(depth_l) 63 } 64 wg.Wait() 65 66 for depth := minDepth; depth <= maxDepth; depth += 2 { 67 fmt.Printf("%d\t trees of depth %d\t check: %d\n", 68 result_trees[depth], depth, result_check[depth], 69 ) 70 } 71 fmt.Printf("long lived tree of depth %d\t check: %d\n", 72 maxDepth, longLivedTree.ItemCheck(), 73 ) 74 } 75 76 func bottomUpTree(item, depth int) *Node { 77 if depth <= 0 { 78 return &Node{item, nil, nil} 79 } 80 return &Node{item, 81 bottomUpTree(2*item-1, depth-1), 82 bottomUpTree(2*item, depth-1), 83 } 84 } 85 86 type Node struct { 87 item int 88 left, right *Node 89 } 90 91 func (self *Node) ItemCheck() int { 92 if self.left == nil { 93 return self.item 94 } 95 return self.item + self.left.ItemCheck() - self.right.ItemCheck() 96 }