To calculate the runtime of a function I'm using
inicio=time.time()
# código
fim=time.time()
How do I calculate time repeatedly and then calculate the average of that time?
To calculate the runtime of a function I'm using
inicio=time.time()
# código
fim=time.time()
How do I calculate time repeatedly and then calculate the average of that time?
You can put the code snippet you are measuring to execute 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 timeit
module:
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 may notice that in both, either "manually" or through the library, the implementations are quite similar.
An interesting way that Python allows you to do is to create a decorator who manages this 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 time trial calls:
for _ in range(100):
foo(1, 2)
Then review 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 at Repl.it .
Tip: I used a simple list to manage times, but you can easily abstract this into a more complex structure that already manages all the logic you need, whether you are calculating minimums and maximums, averaging , standard deviation, variance, or generating the graph.