python程序執行時間
The execution time of a program is defined as the time spent by the system to execute the task. As we all know any program takes some execution time but we don't know how much. So, don't worry, in this tutorial we will learn it by using the datetime module and also we will see the execution time for finding the factorial of a large number. A large number will be provided by the user and we have to calculate the factorial of a number, also we have to find the execution time of the factorial program. Before going to write the Python program, we will try to understand the algorithm.
程序的執行時間定義為系統執行任務所花費的時間。 眾所周知,任何程序都需要一些執行時間,但我們不知道需要多少時間。 因此,不用擔心,在本教程中,我們將通過使用datetime模塊來學習它,并且還將看到查找大量因數的執行時間。 用戶將提供大量的數字,我們必須計算數字的階乘,也必須找到階乘程序的執行時間 。 在編寫Python程序之前,我們將嘗試了解該算法。
Algorithm to find the execution time of a factorial program:
查找階乘程序的執行時間的算法:
Initially, we will import the datetime module and also the math module(to find the factorial) in the Program. Take the value of a number N from the user.
最初,我們將在程序中導入datetime模塊和math模塊(以找到階乘)。 從用戶處獲取數字N的值。
Take the value of a number N from the user.
從用戶處獲取數字N的值。
Find the initial time by using now() function and assign it to a variable which is t_start.
使用now()函數查找初始時間,并將其分配給t_start變量。
Calculate the factorial of a given number(N) and print it.
計算給定數字的階乘并打印。
Here, we will also find the current time and assign it to a variable which is t_end.
在這里,我們還將找到當前時間,并將其分配給t_end變量。
To know the execution time simply find the difference between the t_end and t_start i.e t_end - t_start.
要知道執行時間只需找到t_end和t_start即t_end之間的區別- t_start。
Now, let's start writing the Python program by simply implementing the above algorithm.
現在,讓我們開始通過簡單地實現上述算法來編寫Python程序。
# importing the modules
from datetime import datetime
import math
N=int(input("Enter the value of N: "))
t_start=datetime.now()
s=math.factorial(N)
print("factorial of the number:",s)
t_end=datetime.now()
e=t_end-t_start
print("The execution time for factorial program: ",e)
Output
輸出量
Enter the value of N: 25
factorial of the number: 15511210043330985984000000
The execution time for factorial program: 0:00:00.000022
The output format of the execution time of factorial as "hours: minutes: seconds. microseconds".
階乘執行時間的輸出格式為“小時:分鐘:秒。微秒” 。
翻譯自: https://www.includehelp.com/python/find-the-execution-time-of-a-program.aspx
python程序執行時間