github.com/coyove/nj@v0.0.0-20221110084952-c7f8db1065c3/tests/bench/binarytree.txt (about)

     1  n = 21
     2  use_array = true
     3  
     4  function bottomUpTree(depth)
     5      if (depth <= 0) then return if(use_array, [], {}) end
     6      if use_array then
     7          return [bottomUpTree(depth-1), bottomUpTree(depth-1)]
     8      end
     9      return { left=bottomUpTree(depth-1), right=bottomUpTree(depth-1) } 
    10  end
    11  
    12  function itemCheck(n)
    13      if (#(n) == 0) then return 1 end
    14      if use_array then
    15          return itemCheck(n[0]) + itemCheck(n[1]) + 1
    16      end
    17      return itemCheck(n.left) + itemCheck(n.right) + 1
    18  end
    19  
    20  minDepth = 4 
    21  maxDepth = n 
    22  if (minDepth + 2 > n) then maxDepth = minDepth + 2 end
    23  stretchDepth = maxDepth + 1 
    24  
    25  check_l = itemCheck(bottomUpTree(stretchDepth)) 
    26  print(("stretch tree of depth %d\t check: %v").format(stretchDepth, check_l) )
    27  --return
    28  
    29  longLivedTree = bottomUpTree(maxDepth) 
    30  result = array.make(maxDepth+1) 
    31  
    32  function worker(k, args)
    33      local depth, check = args[0], args[1]
    34      iterations = 1 << (maxDepth - depth + minDepth) 
    35      check = 0 
    36  
    37      for i = 0,iterations do
    38          check = check + itemCheck(bottomUpTree(depth)) 
    39      end
    40      result[depth] = ("%d\t trees of depth %d\t check: %v").format(iterations, depth, check)
    41  end
    42  
    43  payload = []
    44  for depth_l = minDepth,maxDepth,2 do
    45      payload.append([depth_l, check_l])
    46  end
    47  worker.map(payload, os.numcpus)
    48  
    49  for depth = minDepth,maxDepth,2 do
    50      print(result[depth]) 
    51  end
    52  
    53  print(("long lived tree of depth %d\t check: %v\n").format(maxDepth, itemCheck(longLivedTree)))