0

I have a program that has multiple methods. I would like to measure how long it takes for each method to run when they are called.

For example

def func1:
  blah

def func2:
  blah


def main:
  call func1 and func2 and measure their times

is there an easy way to do it.

eyllanesc
  • 235,170
  • 19
  • 170
  • 241
  • Take a look at this post to see how it is done. https://stackoverflow.com/a/25823885/9610015 – Hussain Hassam Apr 07 '18 at 03:50
  • Possible duplicate of [How do I get time of a Python program's execution?](https://stackoverflow.com/questions/1557571/how-do-i-get-time-of-a-python-programs-execution) – eyllanesc Apr 07 '18 at 04:01

3 Answers3

1

Here's a code timing setup I wrote for myself, I use python 2.7

#!python2

import timeit

runs = 100
totalTime = 0.0; average = 0.0
testTimes = []

for i in range(runs):
    startTimer = timeit.default_timer()

    # >>>>> code to be tested goes here <<<<<

    endTimer = timeit.default_timer()

    timeInterval = endTimer - startTimer
    testTimes.append(timeInterval)
    totalTime += timeInterval

    # running below statement causes each run longer to complete
    # print '\n', '%1.4f' % timeInterval + ' seconds'

print
print '   Total time:', '%1.4f' % totalTime + ' seconds'
print 'Shortest time:', '%1.4f' % min(testTimes) + ' seconds'
print ' Longest time:', '%1.4f' % max(testTimes) + ' seconds'
print ' Average time:', '%1.4f' % (totalTime / runs) + ' seconds'
Michael Swartz
  • 858
  • 2
  • 15
  • 27
1

I find the following piece of re-usable code handy when testing functions.

import timeit    

def timed_function(f, *args, **kwargs):
    myname = str(f).split(' ')[1]
    def new_func(*args, **kwargs):
        timer1 = timeit.default_timer()
        result = f(*args, **kwargs)
        timer2 = timeit.default_timer()
        delta = timer2 - timer1
        print('Function {} Time = {:6.3f}ms'.format(myname, delta*1000))
        return result
    return new_func

You can use it to decorate any function and then it will print the original function's name and execution time every time you run it.

Something like this:

@timed_function
def func1():
    return sum([0.5 for i in range(10000)])

y = func1()

Code output: Function func1 Time = 0.849ms

[I got the idea from here.]

Bill
  • 10,323
  • 10
  • 62
  • 85
0

If you're running code from a separate file, perf_counter is the way to go. For example,

from time import perf_counter

def main():
    start = perf_counter()
    # Do stuff.
    print(perf_counter() - start)

If you're testing code in the shell, there's an even easier way: the timeit module. It has two main functions: timeit and repeat. The former is simply a timer, the latter returns a list of times for different trials. https://docs.python.org/3/library/timeit.html?highlight=timeit#module-timeit Just make sure to pass globals() as the globals argument if you're using imported functions!

Isaac Saffold
  • 1,116
  • 1
  • 11
  • 20