Skip to content

Instantly share code, notes, and snippets.

@deech
Created March 13, 2019 20:58
Show Gist options
  • Save deech/8f585df50dbd662bb5fb5f48a7e159e9 to your computer and use it in GitHub Desktop.
Save deech/8f585df50dbd662bb5fb5f48a7e159e9 to your computer and use it in GitHub Desktop.
Binary tree benchmark [Nim]
import threadpool, strformat, os, strutils, math
type
Tree = ref object
left: Tree
right: Tree
proc deepCopy[T](x: var T, y: T) =
x = y
proc check(t: Tree): int32 =
result = 1
if (t.left != nil and t.right != nil):
result += check t.left
result += check t.right
proc make(depth: int32): Tree =
result = Tree(left: nil, right: nil)
if depth > 0:
result.left = make(depth - 1)
result.right = make(depth - 1)
proc shortLived(depth: int32, iterations: int32): string =
{.push experimental: "parallel".}
var ts = newSeq[FlowVar[Tree]](iterations)
parallel:
for i in 0 .. ts.len-1:
ts[i] = spawn make depth
var sum = 0
for t in ts:
sum += check ^t
{.pop.}
&"{iterations}\t trees of depth {depth}\t check: {sum}"
let minDepth = 4
let maxDepth : int32 =
if paramCount() == 0: 2
else:
try: parseInt(paramStr(1))
except: 2
echo &"stretch tree of depth {maxDepth+1} check: {check(make(maxDepth+1))}"
let longLived = make maxDepth
let numMessages = int(maxDepth/2)
var messages = newSeq[string](numMessages+1)
for i in 2 .. int(maxDepth/2):
let depth = int32(i*2)
let iterations = int32(1 shl (maxDepth - depth + minDepth))
echo iterations , " " , depth
messages[i] = shortLived(depth, iterations)
echo messages
echo check longLived
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment