John Gringus
John Gringus

Reputation: 59

How to time how long my method takes to run?

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.

Upvotes: 0

Views: 133

Answers (3)

Michael Swartz
Michael Swartz

Reputation: 858

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'

Upvotes: 1

Bill
Bill

Reputation: 11613

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.]

Upvotes: 1

Isaac Saffold
Isaac Saffold

Reputation: 1185

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!

Upvotes: 0

Related Questions