简体   繁体   中英

Finding the timing of the program by using timeit function in python

I have 2 different programs. First is called prob1.py which calculates Fibonacci numbers. Second one is called prob2.py which calculates Fibonacci with using memoisation. In third program called prob3.py, I'm trying to print out (n, timing for fib(n)) for prob1.py and (n, timing for MemoFib(n)) for prob2.py range between (0,40).

prob1.py is

import sys

def fib(n):
   if n == 0:
     return (1)
   elif n == 1:
     return (1)
   else:
     return fib(n-1)+fib(n-2)

def main():
result = int(sys.argv[1])
print(fib(result))
main()

and prob2.py is

import sys

array = [0]*101

def MemoFib(n):
if n<=1:
    return 1
else:
    if(array[n-1]==0):
        array[n-1] = MemoFib(n-1)
    if(array[n-2]==0):
        array[n-2] = MemoFib(n-2)
    array[n] = array[n-1] + array[n-2]
    return array[n]

def main():
array = [0]*101   # clears the memo between runs
if int(sys.argv[1]) <= 100:
  print(MemoFib(int(sys.argv[1])))
else:
  print('Enter a value between 0 and 100')
main()

I have the following codes to call these 2 programs to print out what I need however I can't fit it into my codes. Could you fix it, please? If the following code doesn't work, I can use something else too. All I need is to print out (n, Fib(n)) and (n, MemoFib(n)) by using timeit function.

mytime = timeit.Timer( 'fib(0,40)', 'from prob1 import fib' )
delta = mytime.timeit( 40 )
print "40 runs of fib( 1000000 ) took: " + str( delta ) + " seconds."
print ''

setupStr = 'from prob1 import fib'
setupStr += '; import anotherFile'
mytime = timeit.Timer( 'list_concat( anotherFile.a, anotherFile.b)',     setupStr )
print 'calling list_concat from cell.py on a, b, from foo.py:'
delta = mytime.timeit( 5 )
print "1 run of MemoFib( a, b ) took: " + str( delta ) + " seconds."

When you use Timer('fib(0,40)', 'from prob1 import fib') you are setting up the timer to call fib with two arguments which will give you a TypeError telling you that. Instead run the timers in a for loop in prob3.py

EDIT - I have now tested this and know it can be executed.

import timeit

repeats = 100
run_code = 'fib(%d)' # formatting mark to enter each time
for n in range(40):
    # you can just call the .timeit() function from the module
    mytime = timeit.timeit(run_code % n, 'from prob1 import fib', number=repeats)
    print ("fib(%d) repeated %d times took %f seconds"%(n,repeats,mytime))

# similar for other one

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM