Skip to content
This repository

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
Browse code

sped up binary tree by using a C struct

  • Loading branch information...
commit a9f168c8557bcfa59a9ac3c29c3044dddcbba4b4 1 parent b8282cb
Justin Peel authored

Showing 1 changed file with 21 additions and 17 deletions. Show diff stats Hide diff stats

  1. +21 17 binary_tree_cython.pyx
38 binary_tree_cython.pyx
... ... @@ -1,35 +1,39 @@
1   -cdef extern from "binary_tree_cython.h":
2   - object PY_NEW(object, args)
3   - void disable_gc(object)
  1 +from libc.stdlib cimport malloc, free
4 2
5   -cdef class Node:
6   - cdef Node left
7   - cdef Node right
8   - cdef long item
  3 +cdef struct Node:
  4 + Node *left
  5 + Node *right
  6 + int item
9 7
10   -cdef Node make_tree(long item, long depth):
11   - cdef Node t = <Node>PY_NEW(Node, ())
  8 +cdef Node *make_tree(int item, int depth):
  9 + cdef Node *t = <Node*>malloc(sizeof(Node))
12 10 t.item = item
13 11 if depth:
14 12 depth -= 1
15 13 item <<= 1
16 14 t.left = make_tree(item - 1, depth)
17 15 t.right = make_tree(item, depth)
  16 + else:
  17 + t.left = NULL
  18 + t.right = NULL
18 19 return t
19 20
20   -cdef long check_tree(Node t):
21   - if t.left is None:
22   - return t.item
  21 +cdef int check_tree(Node* t):
  22 + cdef int tmp
  23 + if t.left:
  24 + tmp = t.item + check_tree(t.left) - check_tree(t.right)
23 25 else:
24   - return t.item + check_tree(t.left) - check_tree(t.right)
  26 + tmp = t.item
  27 + free(t)
  28 + return tmp
25 29
26 30 def main(int n):
27 31
28 32 # By definition, trees can't have cycles. However, Python's garbage
29 33 # collector will do lots of wasteful tree traversals to try to collect
30 34 # circular references. Normal reference counting still happens.
31   - import gc
32   - gc.disable()
  35 + #import gc
  36 + #gc.disable()
33 37
34 38 cdef int min_depth, max_depth, stretch_depth, depth
35 39 min_depth = 4
@@ -37,7 +41,7 @@ def main(int n):
37 41 stretch_depth = max_depth + 1
38 42
39 43 cdef int i, iterations
40   - cdef long check
  44 + cdef int check
41 45
42 46 print "stretch tree of depth %d\t check:" % stretch_depth, check_tree(make_tree(0, stretch_depth))
43 47
@@ -52,7 +56,7 @@ def main(int n):
52 56 check += check_tree(make_tree(-i, depth))
53 57
54 58 print "%d\t trees of depth %d\t check:" % (iterations * 2, depth), check
55   - iterations /= 4
  59 + iterations >>= 2
56 60
57 61 print "long lived tree of depth %d\t check:" % max_depth, check_tree(long_lived_tree)
58 62

0 comments on commit a9f168c

Please sign in to comment.
Something went wrong with that request. Please try again.