最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

Python中計(jì)時(shí)程序運(yùn)行時(shí)間的幾種常用方法

 更新時(shí)間:2025年04月18日 10:16:39   作者:NameError_sfj  
這篇文章主要介紹了Python中計(jì)時(shí)程序運(yùn)行時(shí)間的幾種常用方法,分別是一般方法、基于上下文管理器和基于裝飾器,每種方法都有其適用場(chǎng)景和優(yōu)缺點(diǎn),文中通過(guò)代碼介紹的非常詳細(xì),需要的朋友可以參考下

前言

在實(shí)際工作中,我們常常需要知道程序的實(shí)際運(yùn)行時(shí)間(wall-clock time, real time)。本文就介紹了幾種在Python中計(jì)時(shí)程序運(yùn)行耗時(shí)的方法。

1. 一般方法

最為常見(jiàn)的方法,就是在代碼的開(kāi)頭和結(jié)尾分別獲取時(shí)間戳,然后兩者之差便是程序運(yùn)行時(shí)間。

import time

def do_something(nsec=0):
	if isinstance(nsec, (int, float)):
		time.sleep(nsec)  # 模擬程序運(yùn)行耗時(shí)

if __name__ == "__main__":
	start_time	= time.perf_counter()  # 記錄開(kāi)始時(shí)間戳
	do_something(3)
	do_something(1)
	do_something(0.5)
	end_time = time.perf_counter()  # 記錄結(jié)束時(shí)間戳
	print(f"耗時(shí) {end_time - start_time:.3f} s")

這是最簡(jiǎn)單直接的方法,但問(wèn)題是當(dāng)需要計(jì)時(shí)的部分很多的時(shí)候,會(huì)導(dǎo)致大量的重復(fù)代碼。

2. 基于上下文管理器

相比之下,使用Python的上下文管理器(context manager)是更加優(yōu)雅,復(fù)用性更好的解決方案。Python的上下文管理器機(jī)制是用來(lái)更加方便地管理如文件、數(shù)據(jù)庫(kù)連接、鎖等資源的,確保在使用結(jié)束后恰當(dāng)?shù)仃P(guān)閉及釋放資源,以避免造成泄露。
然而,上下文管理器的用途不僅限于資源的管理,其適合于所有的代碼開(kāi)始和結(jié)束的成對(duì)操作,就比如計(jì)時(shí)程序的運(yùn)行時(shí)間。

import time 

class Timer:
	"""
	按照 xxh xxm xxs格式計(jì)時(shí)程序運(yùn)行時(shí)間的計(jì)時(shí)上下文管理器
	"""
	def __init__(self, code_part):
		self._part = code_part
		
	def __enter__(self):
		self._enter_time = time.perf_counter()
		
	def __exit__(self, *exc_args):  # 不做異常處理,因此將異常相關(guān)的參數(shù)打包
		time_span = time.perf_counter() - self._enter_time
		hours, seconds = divmod(time_span, 3600)
		minutes, seconds = divmod(seconds, 60) 
		print(f"{self._part}耗時(shí) {int(hours)}h {int(minutes)}m {seconds:.2f}s")

def do_something(nsec=0):
	if isinstance(nsec, (int, float)):
		time.sleep(nsec)  # 模擬程序運(yùn)行耗時(shí)

if __name__ == "__main__":
	with Timer("Main"):
		with Timer("Part1"):
			do_something(0.3)
		with Timer("Part2"), open("demo_file.txt", "wt") as f:
			f.write("Hello, World\n")
			do_something(2)
		do_something(1)

3. 基于裝飾器

使用Python的裝飾器特性,可以十分方便地在函數(shù)水平添加計(jì)時(shí)器,計(jì)時(shí)單個(gè)函數(shù)的運(yùn)行時(shí)間。

import time
from functools import wraps

def timer(func):
	@wraps(func)
	def inner(*args, **kwargs):
		start_time = time.perf_counter()
		retval = func(*args, **kwargs)
		time_span = time.perf_counter() - start_time
		hours, seconds = divmod(time_span, 3600)
		minutes, seconds = divmod(seconds, 60) 
		print(f"{func.__name__}耗時(shí) {int(hours)}h {int(minutes)}m {seconds:.2f}s")
		return retval
	return inner

@timer
def do_something(nsec=0):
	if isinstance(nsec, (int, float)):
		time.sleep(nsec)  # 模擬程序運(yùn)行耗時(shí)

@timer
def main():
	do_something(1)
	time.sleep(0.5)

if __name__ == "__main__":
	main()	

總結(jié) 

到此這篇關(guān)于Python中計(jì)時(shí)程序運(yùn)行時(shí)間的幾種常用方法的文章就介紹到這了,更多相關(guān)Python計(jì)時(shí)程序運(yùn)行時(shí)間方法內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

最新評(píng)論

奎屯市| 海晏县| 隆尧县| 郸城县| 同仁县| 马山县| 长沙县| 潍坊市| 鸡泽县| 丹棱县| 北安市| 石嘴山市| 高台县| 文登市| 辽阳市| 镶黄旗| 定安县| 宁阳县| 四子王旗| 黔西县| 霍山县| 肇庆市| 司法| 加查县| 盐城市| 嘉黎县| 铜陵市| 定州市| 诏安县| 乐东| 绥宁县| 汪清县| 万载县| 门头沟区| 扶绥县| 定南县| 宁南县| 正宁县| 金坛市| 德安县| 夹江县|