¿Cómo verificar el tiempo de ejecución del script de Python?

En este artículo, discutiremos cómo obtenemos el tiempo de ejecución de un programa de Python .

Hay muchos módulos de python como time , timeit y DateTime en Python que pueden almacenar la hora a la que se ejecuta una sección particular del programa. Al manipular u obtener la diferencia entre los tiempos de inicio y finalización en los que se ejecuta una sección en particular, podemos calcular el tiempo que tomó ejecutar la sección. 

Los siguientes métodos se pueden utilizar para calcular la diferencia horaria:

  • El módulo de tiempo en Python proporciona varias funciones relacionadas con el tiempo. Este módulo se incluye en los módulos de utilidad estándar de Python. El método time.time() del módulo Time se usa para obtener el tiempo en segundos desde la época. El manejo de los segundos bisiestos depende de la plataforma.
  • El módulo Python DateTime define una función que se puede usar principalmente para obtener la hora y la fecha actuales. función now() Devuelve la fecha y hora local actual, que se define en el módulo DateTime.
  • El módulo timeit ejecuta su fragmento de código millones de veces (el valor predeterminado es 1000000) para que obtenga la medida estadísticamente más relevante del tiempo de ejecución del código.

Método 1: verifique el tiempo de ejecución de Python usando el módulo de tiempo

Ejemplo 1

Cálculo del tiempo usando el módulo de tiempo y la función time.time() . Hemos calculado el tiempo del programa anterior que salió del orden 10^-3. Podemos verificar el tiempo aumentando el número de cálculos usando los mismos algoritmos.

Python3

# program to compute the time
# of execution of any python code
import time
 
# we initialize the variable start
# to store the starting time of
# execution of program
start = time.time()
 
# we can take any program but for
# example we have taken the below
# program
a = 0
for i in range(1000):
    a += (i**100)
 
# now we have initialized the variable
# end to store the ending time after
# execution of program
end = time.time()
 
# difference of start and end variables
# gives the time of execution of the
# program in between
print("The time of execution of above program is :", end-start)

Producción:

The time of execution of above program is : 0.001995563507080078

Ejemplo 2

Comprobación de los tiempos de ejecución del programa para diferentes números de cálculos. Vemos una tendencia general en el aumento del tiempo de cómputo por un aumento en el número de ejecución. Sin embargo, es posible que no muestre ninguna tendencia lineal o incrementos fijos.

Python3

# program to compute the time
# of execution of any python code
# for different number of computations
import time
 
# we initialize a for loop and in each
# iterations store the time of start
# and end of the iterations
for j in range(100, 1100, 100):
    start = time.time()
 
    # program to iterate the range of
    # below loop increasing the value
    # in each iterations
    a = 0
    for i in range(j):
        a += (i**100)
 
    # the end variable to store the
    # ending time after execution of
    # program after each iterations
    end = time.time()
 
    # difference of start and end variables
    # gives the time of execution of the program
    # in between in each iterations
    print("Time for execution of program for {} order of computations: {}".format(
        j, round(end-start, 10)))

Producción:

How to check the execution time of Python script ?

 

Método 2: verifique el tiempo de ejecución de Python usando el módulo DateTime

Usando el módulo DateTime en python y la función datetime.now .

Python3

from datetime import datetime
 
# we initialize the variable start to
# store the starting time of execution
# of program
start = datetime.now()
 
# we can take any program but for
# example we have taken the below
# program
a = 0
for i in range(1000):
    a += (i**100)
 
# now we have initialized the variable
# end to store the ending time after
# execution of program
end = datetime.now()
 
# difference of start and end variables
# gives the time of execution of the
# program in between
print("The time of execution of above program is :",
      str(end-start)[5:])

Producción:

The time of execution of above program is : 00.001996

Método 3: verifique el tiempo de ejecución de Python usando el módulo timeit

Esto nos daría el tiempo de ejecución de cualquier programa. Este módulo proporciona una forma sencilla de encontrar el tiempo de ejecución de pequeños fragmentos de código Python. Proporciona el método timeit() para hacer lo mismo. La función del módulo timeit.timeit (stmt, setup, timer, number) acepta cuatro argumentos:

  • stmt que es la declaración que desea medir; por defecto es ‘aprobado’.
  • configuración que es el código que ejecuta antes de ejecutar el stmt; por defecto es ‘aprobado’. Generalmente usamos esto para importar los módulos requeridos para nuestro código.
  • temporizador que es un objeto timeit.Timer; generalmente tiene un valor predeterminado razonable para que no tenga que preocuparse por eso.
  • El número que es el número de ejecuciones que le gustaría ejecutar la sentencia.

Python3

# program to compute the time of
# execution of any python code using timit
 
# importing the required module
import timeit
 
# code snippet to be executed only once
mysetup = "from math import sqrt"
 
# code snippet whose execution time
# is to be measured
mycode = '''
def example():
    mylist = []
    for x in range(100):
        mylist.append(sqrt(x))
'''
 
# timeit statement
print("The time of execution of above program is :",
      timeit.timeit(setup=mysetup,
                    stmt=mycode,
                    number=10000))

Producción:

The time of execution of above program is : 0.0023286999994525104

Publicación traducida automáticamente

Artículo escrito por ss6437p y traducido por Barcelona Geeks. The original can be accessed here. Licence: CCBY-SA

Deja una respuesta

Tu dirección de correo electrónico no será publicada. Los campos obligatorios están marcados con *