| 1 |
module benchmark.binarytrees |
|---|
| 2 |
|
|---|
| 3 |
// n = 16, 94.764 sec |
|---|
| 4 |
|
|---|
| 5 |
function BottomUpTree(item, depth) |
|---|
| 6 |
{ |
|---|
| 7 |
if(depth > 0) |
|---|
| 8 |
{ |
|---|
| 9 |
local i = item + item |
|---|
| 10 |
--depth |
|---|
| 11 |
|
|---|
| 12 |
local left = BottomUpTree(i - 1, depth) |
|---|
| 13 |
local right = BottomUpTree(i, depth) |
|---|
| 14 |
|
|---|
| 15 |
return [item, left, right] |
|---|
| 16 |
} |
|---|
| 17 |
else |
|---|
| 18 |
return [item] |
|---|
| 19 |
} |
|---|
| 20 |
|
|---|
| 21 |
function ItemCheck(tree) |
|---|
| 22 |
if(#tree == 3) |
|---|
| 23 |
return tree[0] + ItemCheck(tree[1]) - ItemCheck(tree[2]) |
|---|
| 24 |
else |
|---|
| 25 |
return tree[0] |
|---|
| 26 |
|
|---|
| 27 |
function main(N) |
|---|
| 28 |
{ |
|---|
| 29 |
local n = 16 |
|---|
| 30 |
|
|---|
| 31 |
if(isString(N)) |
|---|
| 32 |
try n = toInt(N); catch(e) {} |
|---|
| 33 |
|
|---|
| 34 |
local timer = time.Timer.clone() |
|---|
| 35 |
timer.start() |
|---|
| 36 |
|
|---|
| 37 |
local mindepth = 4 |
|---|
| 38 |
local maxdepth = mindepth + 2 |
|---|
| 39 |
|
|---|
| 40 |
if(maxdepth < n) |
|---|
| 41 |
maxdepth = n |
|---|
| 42 |
|
|---|
| 43 |
{ |
|---|
| 44 |
local stretchdepth = maxdepth + 1 |
|---|
| 45 |
local stretchtree = BottomUpTree(0, stretchdepth) |
|---|
| 46 |
writefln("stretch tree of depth {}\t check: {}", stretchdepth, ItemCheck(stretchtree)) |
|---|
| 47 |
} |
|---|
| 48 |
|
|---|
| 49 |
local longlivedtree = BottomUpTree(0, maxdepth) |
|---|
| 50 |
|
|---|
| 51 |
for(depth: mindepth .. maxdepth + 1, 2) |
|---|
| 52 |
{ |
|---|
| 53 |
local iterations = 1 << (maxdepth - depth + mindepth) |
|---|
| 54 |
local check = 0 |
|---|
| 55 |
|
|---|
| 56 |
for(i: 0 .. iterations) |
|---|
| 57 |
check += ItemCheck(BottomUpTree(1, depth)) + ItemCheck(BottomUpTree(-1, depth)) |
|---|
| 58 |
|
|---|
| 59 |
writefln("{}\t trees of depth {}\t check: {}", iterations * 2, depth, check) |
|---|
| 60 |
} |
|---|
| 61 |
|
|---|
| 62 |
writefln("long lived tree of depth {}\t check: {}", maxdepth, ItemCheck(longlivedtree)) |
|---|
| 63 |
|
|---|
| 64 |
timer.stop() |
|---|
| 65 |
writefln("Took {} sec", timer.seconds()) |
|---|
| 66 |
} |
|---|