Measuring the run time of a function

Asked

Viewed 29,788 times

13

How can I measure the running time of a Python function?

In C#, I can use the class Stopwatch in that way

var sw = new Stopwatch();
sw.Start();
AlgumaFuncao();
sw.Stop();

WriteLine(sw.ElapsedTicks);

3 answers

14


You can use time.time():

import time

inicio = time.time()
funcao()
fim = time.time()
print(fim - inicio)

8

Basically you should take the start and end times of the test and then check the difference.

There are several options for how to take a break in Python, such as the functions of the module time, which takes both real values (system time) and relative values (counters between one call and another of the function).

However from Python 2.3 there is the module timeit, that according to the documentation:

This module provides a simple way to time small bits of Python code. It has Both a Command-Line Interface as well as a callable one. It avoids a number of common traps for Measuring Execution times.

In free translation:

This module provides a simple way to measure small chunks of Python code. It has both an interface via line command and a redeemable interface. It avoids a number of common pranks in measuring run times.

The function to be used for this module would be the default_timer(), which according to the documentation:

Sets the default timer, in a Platform-specific Manner. On Windows, time.clock() has microsecond Granularity, but time.time()’s Granularity is 1/60th of a Second. On Unix, time.clock() has 1/100th of a Second Granularity, and time.time() is Much more precise. On either Platform, default_timer() measures Wall clock time, not the CPU time. This Means that other processes running on the same computer may interfere with the timing.

In free translation:

Sets a standard, platform-specific timer. In Windows, time.clock() has microsecond granularity, but time.time() granularity is 1/60 seconds. In Unix, time.clock() has a granularity of 1/100 seconds, and time.time() is much more accurate. On any platform, default_timer() measures real time, not CPU time. This means that other processes running on the same computer can interfere with this time measurement.

Up to Python 2, the timeit.default_timer() choose the one that is best for your operating system from the time.time() and the time.clock(), in Python 3 he always chooses the time.perf_counter(). Therefore, the timeit.default_timer() is the most robust option among Python versions and operating systems.

Example of how the measurement would look using this module:

import time
import timeit


def alguma_funcao():
    for i in range(1, 5):
        time.sleep(1)

inicio = timeit.default_timer()
alguma_funcao()
fim = timeit.default_timer()
print ('duracao: %f' % (fim - inicio))

An example of a possible execution result above:

duration: 4.002503

2

I believe that the timeit function of the timeit module is simpler and more robust to measure the execution time of some code in Python. With it, you don’t need to calculate the execution delta because that’s exactly the value it returns. In addition, you can control how many executions of the code you will do, which allows you to calculate an average of the execution time.

Here is an example of three functions that generate a list of 10 integers:

def f1():
    return list(range(10))

def f2():
    return [x for x in range(10)]

def f3():
    lst = []
    i = 0
    while i < 10:
        lst.append(i)
        i += 1
    return lst

The calculation:

from timeit import timeit

v1 = timeit('f1()', 'from __main__ import f1', number=100)
v2 = timeit('f2()', 'from __main__ import f2', number=100)
v3 = timeit('f3()', 'from __main__ import f3', number=100)

print(v1, v2, v3)

Browser other questions tagged

You are not signed in. Login or sign up in order to post.