Search code examples
pythontiming

Timings of functions inside python script


I've got a script with several complex functions, which looks something like this

import time

def function1(a,b,c):
   print(a,b,c)

def function2(d,e,f):
   print(d,e,f)
...
...
def function7(g,h,i):
   print(g,h,i)

I am trying to record the timing for each function and then make a dataframe with all the timings for analysis. This is what I have attempted:

start1 = time.time()
function1(a,b,c)
end1 = time.time()
func1_time = end - start

start2 = time.time()
function2(d,e,f)
end2 = time.time()
func2_time = end - start
...
...
start7 = time.time()
function7(g,h,i)
end7 = time.time()
func7_time = end - start

Above is a basic method using time.time, however, is there a more elegant/convenient way to carry this out?


Solution

  • When you see variable1, variable2, etc. and you want your code to look more elegant, the answer is in 90% cases either a list or a dictionary:

    funs = [function1, function2, function3]
    times = []
    for fun in funs:
        start = time.time()
        fun(a,b,c)
        end = time.time()
        times.append(end - start)