I need a code that calculates nth fibonacci number as well as giving me the time used to calculate it, in python.
def fib(n):
if n==0 or n==1: return 1
else: return fib(n-1)+fib(n-2)
The calculation of the number step must use a such method.
Use the
timeitmodule to time the function:Output:
To directly answer the question in the title, you can use
time.time()to get the current time since the epoch in seconds and keep calculating the subsequent fibonacci number until the time limit is reached. I’ve chosen to use an efficient method of computing fibonacci numbers below to give you a better demonstrating of this concept.Sample output: