I want to write a function which behaves exactly similar to the given function, except that it prints the time consumed in executing it. Just like this:
>>> fib = profile(fib)
>>> fib(20)
time taken: 0.1 sec
10946
This is my code,and it will print message in each function call.
import time
def profile(f):
def g(x):
start_time = time.clock()
value = f(x)
end_time = time.clock()
print('time taken: {time}'.format(time=end_time-start_time))
return value
return g
@profile
def fib(n):
if n is 0 or n is 1:
return 1
else:
return fib(n-1) + fib(n-2)
My code above will print a message 'taken time:...' for each fib(n-1).So there will be many many messages 'taken time:...'. Can I find a way to just print executing time of fib(20) not every executing time of fib(n-1)?