"Profile function"
which takes a function as argument and returns a new function, which
behaves exactly similar to the given function, except that it prints the
time consumed in executing it.
We can explain this function in Python .The function is takes another function as argument and behaves exactly like the given function but it also gives the execution time of
given function
1: import time
2: def fib(n):
3: if n is 0 or n is 1:
4: return 1
5: else:
6: return fib(n-1) + fib(n-2)
7: def profile(f):
8: cache={}
9: def g(x):
10: tim=0
11: if x not in cache:
12: start = time.time()
13: cache[x]=f(x)
14: tim=time.time()-start
15: return str(tim)+' sec'
16: return g
17: f= profile(fib)
18: print f(20)
Now we can just go through this program first look for the core function "profile()"
1: def profile(f):
2: cache={}
3: def g(x):
4: tim=0
5: if x not in cache:
6: start = time.time()
7: cache[x]=f(x)
8: tim=time.time()-start
9: return str(tim)+' sec'
10: return g
Profile function takes a function and store each execution in a cache and count the execution time using the library module "time" and finally returns the execution time of the given function
Now we can go through the output of the program which takes a "fib(20)"
as function and returns its execution time as 0.00328707695007 seconds.
execution time is dipends upon the hardware of the system where program is
running
No comments:
Post a Comment