Created
June 8, 2018 01:07
-
-
Save msullivan/8e8f4713bc1e476d793831f50a3a601c to your computer and use it in GitHub Desktop.
microbenchmark
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from typing import cast | |
class Tree: | |
def accept(self, v: 'TreeVisitor') -> object: | |
pass | |
class Leaf(Tree): | |
def accept(self, v: 'TreeVisitor') -> object: | |
return v.visit_leaf(self) | |
class Node(Tree): | |
def __init__(self, value: int, left: Tree, right: Tree) -> None: | |
self.value = value | |
self.left = left | |
self.right = right | |
def accept(self, v: 'TreeVisitor') -> object: | |
return v.visit_node(self) | |
class TreeVisitor: | |
def visit_leaf(self, x: Leaf) -> object: pass | |
def visit_node(self, x: Node) -> object: pass | |
class SumVisitor(TreeVisitor): | |
def sum(self, x: Tree) -> int: | |
return cast(int, x.accept(self)) | |
def visit_leaf(self, x: Leaf) -> object: | |
return 0 | |
def visit_node(self, x: Node) -> object: | |
return x.value + self.sum(x.left) + self.sum(x.right) | |
def sum_tree(x: Tree) -> int: | |
return SumVisitor().sum(x) | |
def lol(n: int) -> Tree: | |
if n == 0: | |
return Leaf() | |
child = lol(n - 1) | |
return Node(n, child, child) | |
def bench_sum_tree(x: Tree) -> None: | |
for i in range(100000): | |
sum_tree(x) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment