How do I calculate the average running time of a function?

Asked

Viewed 424 times

0

To calculate the execution time of a function I am using

inicio=time.time()
# código 
fim=time.time()

How do I calculate the time repeatedly and then calculate the average of that time?

2 answers

3


You can place the snippet of code you are measuring execution within a loop:

import time

REPETICOES = 10
tempos = []
for vezes in range(0, REPETICOES):
    inicio = time.time()
    # ... o código a medir entra aqui ... #
    fim = time.time()
    tempos.append(fim - inicio)

media = sum(tempos) / REPETICOES

Or use the module timeit:

import timeit

REPETICOES = 10

# o seu código fica dentro de uma string mesmo
meu_codigo = """
j = 0
for i in range(0,999):
    j += i * j
"""

tempo = timeit.timeit(stmt=meu_codigo, number=REPETICOES)
print(tempo / REPETICOES)

But you can see that in both, whether "manually" or through the library, the implementations are quite similar.

1

An interesting way that Python lets you do it is to create a decorator that manages it for you:

def time_statistics(func):
    def wrapper(*args, **kwargs):
        start = time.time()
        result = func(*args, **kwargs)
        end = time.time()

        if not hasattr(wrapper, 'times'):
            wrapper.times = []

        wrapper.times.append(end - start)
        return result

    return wrapper

So in the function you want to analyze, just do:

@time_statistics
def foo(a, b):
    return a + b

Make calls to test time:

for _ in range(100):
    foo(1, 2)

Then analyze the results:

print('Tempo mínimo [s]: ', min(foo.times))
print('Tempo máximo [s]: ', max(foo.times))
print('Média de tempo [s]: ', sum(foo.times) / len(foo.times))

See working on Repl.it.

Tip: I used a simple list to manage the times, but you can easily abstract it into a more complex structure that already manages all the logic you need, whether it’s calculating minimums and maximums, calculating the mean, standard deviation, variance, or generating the graph.

Browser other questions tagged

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