Ismycode |.
Есть несколько способов измерения прошедшего времени в Python. Доступные модули время , Время течения , а также * Datetime * измерить прошедшее время.
Использование модуля времени
Мы можем использовать модуль времени для расчета времени, прошедшего в выполнении кода или метода в зависимости от вашей потребности. Существует четыре шага, связанных с измерением времени, прошедшегося при выполнении кода в модуль времени.
Шаг 1: Импортировать модуль времени
Шаг 2: Сохраните отметку времени до переменной при начнете выполнения кода, используя time.perf_counter ()
функция
Шаг 3: Сохраните отметку времени до переменной в конце кода, выполняющего с помощью time.perf_counter ()
функция
Шаг 4: Распечатайте разницу между временем конца и начала, чтобы получить фактическое время выполнения.
Пример использования модуля времени
# import time module import time # start the time and capture it in a variable start = time.perf_counter() # Program to read the entire file (absolute path) using read() function with open("C:/Projects/Tryouts/python.txt", "r") as file: content = file.read() print(content) file.close() # capture the end time and store it in a variable end = time.perf_counter() print('The total time taken to execute code is ', end - start)
Выход
Hello Welcome to Python Tutorial Cheers Appending the content Python The total time taken to execute code is 0.05468999221
Использование модуля Timeit.
Время течения
Модуль часто используется для измерения прошедшего времени меньших фрагментов кода. Мы также можем использовать Timeit ()
Функция, которая выполняет анонимную функцию с несколькими выполнениями.
# import timeit module import timeit # start the time and capture it in a variable start = timeit.default_timer() # Program to read the entire file (absolute path) using read() function with open("C:/Projects/Tryouts/python.txt", "r") as file: content = file.read() print(content) file.close() # capture the end time and store it in a variable end = timeit.default_timer() print('The total time taken to execute code is ', end - start)
Выход
Hello Welcome to Python Tutorial Cheers Appending the content Python The total time taken to execute code is 0.005783799999999999
TimeIt.Timeit ()
Функция может сделать другую функцию в качестве аргумента, и он может выполнить метод несколько раз, указав значение в аргументе числа.
# import timeit module from os import read from time import sleep import timeit def readfile(): sleep(2) # Program to read the entire file (absolute path) using read() function with open("C:/Projects/Tryouts/python.txt", "r") as file: content = file.read() file.close() return content t = timeit.timeit(lambda: readfile(), number=10) print('The total time taken to execute code is ', t)
Выход
The total time taken to execute code is 20.1075041
Обычно для расчета производительности нам необходимо несколько раз выполнять код и получить среднюю производительность. Мы можем достичь его, используя timeit.repeat ()
Функция, как показано ниже.
# import timeit module from os import read from time import sleep import timeit def readfile(): sleep(1) # Program to read the entire file (absolute path) using read() function with open("C:/Projects/Tryouts/python.txt", "r") as file: content = file.read() file.close() return content t = timeit.repeat(lambda: readfile(), number=10, repeat=5) print('The total time taken to execute code is ', t)
Выход
The total time taken to execute code is [10.1566243, 10.102775400000002, 10.128235400000001, 10.065340800000001, 10.076453699999995]
Пост Python Program для измерения прошедшего времени в Python появился первым на INSMYCODE Отказ
Оригинал: “https://dev.to/itsmycode/python-program-to-measure-the-elapsed-time-in-python-24o”