日本免费高清视频-国产福利视频导航-黄色在线播放国产-天天操天天操天天操天天操|www.shdianci.com

學無先后,達者為師

網站首頁 編程語言 正文

Python實現計算函數或程序執行時間_python

作者:牛奶咖啡13 ? 更新時間: 2023-04-26 編程語言

一、需求說明

在Python程序的開發過程中,一些程序需要獲取函數或程序的開始時間、結束時間和時間間隔等內容用來分析和處理內容

二、需求分析

涉及到函數或程序的運行時間,那么必然需要用到時間模塊,只用知道時間模塊中對應的時間信息獲取即可進響應的時間計算。

三、實現方法

3.1、獲取執行時間方式一

①導入time模塊

#導入time模塊
import time

②獲取開始時間、結束時間、時間間隔

#1-獲取開始時間
startTime=time.time()
#需要執行的函數或程序
#2-獲取結束時間
endtime=time.time()
#3-獲取時間間隔
diffrentTime=endtime-startTime

③示例

import time,random
 
def CreateDecimalPerThirtySecods(delaySeconds=3):
    time.sleep(delaySeconds)
    decimal= random.random()
    print(decimal)
 
#測試時間間隔方式一
startTime=time.time()
print('time.time()開始打印隨機小數,開始時間是:',startTime)
time.sleep(3)
endtime=time.time()
print('time.time()3秒后的時間是:',endtime)
diffrentTime=endtime-startTime
print('time.time()相差的時間是:',diffrentTime,' 秒')

示例執行結果如下:

3.2、獲取執行時間方式二

①導入datetime模塊

#導入datetime模塊
import datetime

②獲取開始時間、結束時間、時間間隔

#1-獲取開始時間
startTime=datetime.datetime.now()
#需要執行的函數或程序
#2-獲取結束時間
endtime=datetime.datetime.now()
#3-獲取時間間隔
diffrentTime=(endtime-startTime).seconds

③示例

import datetime,time,random
 
def CreateDecimalPerThirtySecods(delaySeconds=3):
    time.sleep(delaySeconds)
    decimal= random.random()
    print(decimal)
 
#測試時間間隔方式二
print('')
startTime=datetime.datetime.now()
print('datetime.datetime.now()開始打印隨機小數,開始時間是:',startTime)
time.sleep(3)
endtime=datetime.datetime.now()
print('datetime.datetime.now()3秒后的時間是:',endtime)
diffrentTime=(endtime-startTime).seconds
print('datetime.datetime.now()相差的時間是:',diffrentTime,' 秒')

示例執行結果如下:

原文鏈接:https://blog.csdn.net/xiaochenXIHUA/article/details/128969804

欄目分類
最近更新