Search code examples
pythonmatlabtiming

Matlab timeit equivalent in Python for scripts


In Matlab there is

"timeit(F), which measures the typical time (in seconds) required to run the function specified by the function handle F that takes no input argument."

This method returns the median of (I think 13) runs of the function.

Having looked at the methods time and timeit in Python, I can't quite find anything that will let me call from an IPython console, time my script (not function) a number of times, and return either an average or median.

Is there an easy way to do this? or at least time 1 execution, whereby I can make my own loop and average? Thanks


Solution

  • You may want to look at this link and consider the %timeit magic from IPython

    link


    Example:

    Say you define a function you want to test:

    def logtest1(N):
    tr=0.
    for i in xrange(N):
        T= 40. + 10.*random()
        tr = tr + -log(random())/T
    
    from timeit import Timer, timeit, repeat
    runningtime = repeat("logtest1(int(10e5))", setup="from __main__ import logtest1", repeat=5, number=1)
    print (runningtime)
    

    That will run my function logtest1(int(10e5)) 1 time and store the time in the list runningtime then it will repeat the same thing 5 times and store the results in the same list. You can then take the average of the median of that list.