Skip to content

Commit 454238f

Browse files
authored
binarytrees benchmark for swift (#369)
1 parent 256d728 commit 454238f

File tree

2 files changed

+51
-0
lines changed

2 files changed

+51
-0
lines changed
Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,48 @@
1+
import Foundation
2+
3+
let minDepth = UInt32(4)
4+
let maxDepth = CommandLine.argc > 1 ? max(UInt32(CommandLine.arguments[1]) ?? 0, minDepth + 2) : 10
5+
let stretchDepth = maxDepth + 1
6+
let check = Tree(depth: stretchDepth).check
7+
print("stretch tree of depth \(stretchDepth)\t check: \(check)")
8+
9+
let longLivingTree = Tree(depth: maxDepth)
10+
11+
for halfDepth in (minDepth / 2)..<(maxDepth / 2 + 1) {
12+
let depth = halfDepth * 2
13+
let iterations = UInt32(1 << (maxDepth - depth + minDepth))
14+
var chk: UInt32 = 0
15+
for _ in 1...iterations {
16+
chk += Tree(depth: depth).check
17+
}
18+
print("\(iterations)\t trees of depth \(depth)\t check: \(chk)")
19+
}
20+
21+
print("long lived tree of depth \(maxDepth)\t check: \(longLivingTree.check)")
22+
23+
indirect enum Tree {
24+
case Empty
25+
case Node(left: Tree, right: Tree)
26+
27+
init(depth: UInt32) {
28+
if depth > 0 {
29+
self = .Node(left: Tree(depth: depth - 1), right: Tree(depth: depth - 1))
30+
} else {
31+
self = .Node(left: .Empty, right: .Empty)
32+
}
33+
}
34+
35+
var check: UInt32 {
36+
switch self {
37+
case .Node(let left, let right):
38+
switch (left, right) {
39+
case (.Empty, .Empty):
40+
return 1
41+
default:
42+
return 1 + left.check + right.check
43+
}
44+
case .Empty:
45+
return 1
46+
}
47+
}
48+
}

bench/bench_swift.yaml

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,9 @@ problems:
33
- name: helloworld
44
source:
55
- 1.swift
6+
- name: binarytrees
7+
source:
8+
- 1.swift
69
- name: nbody
710
source:
811
- 7.swift

0 commit comments

Comments
 (0)