5 ms·
Using generators in Python you can do this much much faster :D. #!/usr/bin/env python """ Calculate fibonacci numbers using a generator Usage:
by super_mario 8y ago
Using generators in Python you can do this much much faster :D.
#!/usr/bin/env python
"""
Calculate fibonacci numbers using a generator
Usage: fibonacci.py [options] <N>
Arguments:
<N> Print all Fibonacci numbers up to <N>-th
Options:
-h, --help This help
"""
from docopt import docopt
def fibonacci():
"""generate fibonacci numbers"""
a, b = 0, 1
while 1:
yield a
a, b = b, a + b
if __name__ == '__main__':
try:
args = docopt(__doc__)
fib = fibonacci()
for i in range(int(args["<N>"])):
print fib.next()
except ValueError:
print "You must specify valid integer"
except KeyboardInterrupt:
print "Good-bye"
You get something like
$ time ./fibonacci.py 46
0
1
1
2
3
5
8
13
21
34
55
89
144
233
377
610
987
1597
2584
4181
6765
10946
17711
28657
46368
75025
121393
196418
317811
514229
832040
1346269
2178309
3524578
5702887
9227465
14930352
24157817
39088169
63245986
102334155
165580141
267914296
433494437
701408733
1134903170
real 0m0.038s
user 0m0.015s
sys 0m0.018s
- danbruc 8y agoRecursive fibonacci benchmark - you are doing something different in which case you could just evaluate the closed form φⁿ / √5 and be even faster.
- super_mario 8y agoI'm perfectly aware it's meant to be recursive, but it's also a completely pointless test. It's not tail recursive, so you are measuring function call overhead in various languages. But various languages have options to perform much faster anyway, but solution is of course going to be language specific.