import time
import numpy as np

def timeit(somefunc,*args,repeats=100,**kwargs):
    times=[] # initialise array to collect the time for each repetition
    for i in range(repeats): # set loop for number of repetitions to run and time the function that many times

        starttime=time.time() # set start

        ans=somefunc(*args,**kwargs) # run the function 

        endtime=time.time() # set end

        timetaken=endtime-starttime # calculate time from start and end

        times.append(timetaken) # append time for this run to the times list
    mean=np.mean(times) # calculate the average time across the repetitions

    stdev=np.std(times) # get the standard deviation of the times

    error=stdev/(repeats**0.5) # get the error?
    return (ans,mean,error)
downloadDownload PNG downloadDownload JPEG downloadDownload SVG

Tip: You can change the style, width & colours of the snippet with the inspect tool before clicking Download!

Click to optimize width for Twitter