I just read a blog entry about how slow python is compared to Haskell. His code was running at about 33 seconds on my machine. Then he went talking about using psyco to improve his speed. So, I tried running his psyco code and the time came out to be about 1.6 seconds.
And I thought this is just too slow. So here’s my speedy fib. It’s nothing fancy, just uses hash table to increase the speed.
-
from time import time
-
-
fib_hash = {}
-
-
def record(n,v):
-
fib_hash[n] = v
-
return v
-
-
def fib(n):
-
if n == 0 or n == 1:
-
return record(n, n)
-
elif fib_hash.has_key(n):
-
return fib_hash[n]
-
else:
-
return record(n, fib(n-1) + fib(n-2))
-
-
if __name__ == "__main__":
-
start_time = time()
-
for i in range(36):
-
print "n=%d => %d" % (i, fib(i))
-
print "Time elapsed: %f" % (time() - start_time)
The average time for my code was 0.0014~ Woohoo~
[post script]
I tried running my code with psyco, but that made it worse. -_-;; So much for JIT.

Blog RSS