Record runtime in python

Asked

Viewed 1,349 times

3

In Python, I need to do something like:

timer.start()

***Imagine um código de várias linhas aqui***

timer.stop()
print("Tempo de execução: " + timer)

It can be in seconds, minutes anything, someone can give me a help more or less as I can do?

  • Have you tried using the module timeit? https://docs.python.org/3.7/library/timeit.html

2 answers

4


You can use the moduletime.

import time
t1 = time.time()

# código aqui

tempoExec = time.time() - t1
print("Tempo de execução: {} segundos".format(tempoExec))

The line time.time() returns time in seconds since January 1, 1970, and the line time.time() - t1 represents the time variation, that is, how long the program took to run.

0

From what I understand, you’re wanting calcular the time of execução of the program.

In order for this question to have a more obvious answer, let’s assume that we are wanting calcular the execution time the program takes to calculate the fatorial of a number.

In this case we will only examine the calculation of fatorial.

For this we must use the following algorithm...

from time import time

while True:
    try:
        n = int(input('Digite um valor inteiro: '))
        if n <= 0:
            print('\033[31mValor INVÁLIDO! Digite apenas inteiros maiores que "0"!\033[m')
        break
    except:
        print('\033[31mValor INVÁLIDO! Digite apenas números inteiros!\033[m')

instante_inicial = time()
print(f'\033[32mO fatorial de {n} é:')
prod = 1
cont = 0
for c in range(n, 1, -1):
    cont += 1
    x = (n - cont)
    prod *= c
    print(f'{x}', end='')
    print(' x ' if x > 1 else ' = ', end='')
print(f'{prod}')
instante_final = time()
diferenca = (instante_final - instante_inicial) * 1000

print(f'O tempo de execução do calculo do fatorial foi de: {diferenca:.2f} ms')

See here the operation of the programme.

Note that the time has been set in milissegundos.

In this case define two variables that were: instante_inicial and instante_final. Then I calculated the diferença between them and multipliquei for 1000 since it intended to provide the result in milissegundos (ms).

Also note that the greater the complexity of the calculation, the longer the execution time.

Another thing, the time it takes to execute an algorithm is diretamente proporcional the capacity of the machine hardware, that is, processing capacity and memory. In other words, an algorithm that takes 2.00 ms to run on a processor machine dual core, it will take much less time to run on a processor machine i5. In addition, other variables should be taken into account. For example, type of linguagem de programação, if it’s a language interpretada or compilada, etc..

Browser other questions tagged

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