5 ms·
Or you could simply make your python code tail-recursive: $ time python fib.py 40 102334155 real 0m0.013s user 0m0.000s sys 0m0.010s
by ginkgo 17y ago
Or you could simply make your python code tail-recursive:
$ time python fib.py 40
102334155
real 0m0.013s
user 0m0.000s
sys 0m0.010s
- carbon8 17y agoThen you are testing two different things, and if you use tail recursion even Ruby 1.9 still runs it faster than Python. # 400 $ time ruby fib.rb real 0m0.017s user 0m0.010s sys 0m0.006s # 400 $ time python fib.py real 0m0.023s user 0m0.011s sys 0m0.011s
- apgwoz 17y agoOf course you can, but that's not going to work when you run out of stack space. The point of my stupid benchmark was to write the equivalent ruby code, and then the equivalent C code, forgetting the fact that there's a much more optimal way to do it (e.g. write it in scheme with tail calls).
- apgwoz 17y ago> was to write the equivalent ruby code, that should have stated "equivalent python code"
- steveklabnik 17y agoPython does not do tail call optimization.
- gloob 17y agoWhether it does tail call optimization is a different question than whether you can write the algorithm in a tail-recursive manner, though.
- steveklabnik 17y agoYes, but without the optimization, how would it help? Am I just being a n00b?
- apgwoz 17y agoNo, you're not being a n00b. It'll help because the stack usage will grow linearly as opposed to quadratically, as in the case of the naive solution. You'll still overflow the stack without the optimization.
- mbrubeck 17y agoWriting it tail-recursively forces you to switch from the O(2^n) algorithm (which has two recursive calls; you can't put both into tail position) to a more efficient algorithm. You could also write the more-efficient algorithm without tail recursion, of course.