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

Python中計算函數(shù)執(zhí)行時間的五種方法

 更新時間:2025年05月12日 09:43:57   作者:風(fēng)の住む街~  
這篇文章主要為大家詳細介紹了Python中統(tǒng)計函數(shù)執(zhí)行時間的多種方法,例如time.time(),time.perf_counter(),timeit.timeit?()等,有需要的小伙伴可以了解下

1. time.time()

在計算函數(shù)執(zhí)行時間時,這種時最簡潔的一種方式,用兩個時間戳做減法。

import time


def func():
    print('func start')
    time.sleep(1)
    print('func end')


t = time.time()
func()
print(f'coast:{time.time() - t:.4f}s')

結(jié)果為:

func start
func end
coast:1.0003s

這種方法很簡單,也很常用,但是如果想更精確的計算函數(shù)的執(zhí)行時間,就會產(chǎn)生精度缺失。

2. time.perf_counter() 推薦

示例一中注釋掉time.sleep(1),只統(tǒng)計兩個 print 函數(shù)的執(zhí)行時間:

import time


def func():
    print('func start')
    # time.sleep(1)
    print('func end')


t = time.time()
func()
print(f'coast:{time.time() - t:.8f}s')

輸出:

func start
func end
coast:0.0000s

這就說明time.time() 函數(shù)的精度不是特別高,沒法統(tǒng)計執(zhí)行時間極短的函數(shù)耗時。

perf_counter 函數(shù)是在 python3.3 中新添加的,它返回性能計數(shù)器的值,返回值是浮點型,統(tǒng)計結(jié)果包括睡眠的時間,單個函數(shù)的返回值無意義,只有多次運行取差值的結(jié)果才是有效的函數(shù)執(zhí)行時間。

import time


def func():
    print('func start')
    # time.sleep(1)
    print('func end')


t = time.perf_counter()
func()
print(f'coast:{time.perf_counter() - t:.8f}s')

結(jié)果

func start
func end
coast:0.00001500s

結(jié)果并不是 0 秒, 而是一個很小的值,這說明 perf_counter() 函數(shù)可以統(tǒng)計出 print 函數(shù)的執(zhí)行耗時,并且統(tǒng)計精度要比 time.time() 函數(shù)要高,比較推薦作為計時器來使用。

3. timeit.timeit ()

timeit() 函數(shù)有 5 個參數(shù),stmt=‘pass’, setup=‘pass’, timer=, number=1000000, globals=None。

  • stmt 參數(shù)是需要執(zhí)行的語句,默認為 pass
  • setup 參數(shù)是用來執(zhí)行初始化代碼或構(gòu)建環(huán)境的語句,默認為 pass
  • timer 是計時器,默認是 perf_counter()
  • number 是執(zhí)行次數(shù),默認為一百萬
  • globals 用來指定要運行代碼的命名空間,默認為 None。
import time
import timeit


def func():
    print('func start')
    time.sleep(1)
    print('func end')


print(timeit.timeit(stmt=func, number=1))

以上方案中比較推薦使用的是 time.perf_counter() 函數(shù),它具有比較高的精度,同時還被用作 timeit 函數(shù)默認的計時器。

4.裝飾器統(tǒng)計運行耗時

在實際項目代碼中,可以通過裝飾器方便的統(tǒng)計函數(shù)運行耗時。

import time


def cost_time(func):
    def fun(*args, **kwargs):
        t = time.perf_counter()
        result = func(*args, **kwargs)
        print(f'func {func.__name__} cost time:{time.perf_counter() - t:.8f} s')
        return result

    return fun


@cost_time
def test():
    print('func start')
    time.sleep(2)
    print('func end')


if __name__ == '__main__':
    test()

如果有使用異步函數(shù)的需求也可以加上:

import asyncio
import time
from asyncio.coroutines import iscoroutinefunction


def cost_time(func):
    def fun(*args, **kwargs):
        t = time.perf_counter()
        result = func(*args, **kwargs)
        print(f'func {func.__name__} cost time:{time.perf_counter() - t:.8f} s')
        return result

    async def func_async(*args, **kwargs):
        t = time.perf_counter()
        result = await func(*args, **kwargs)
        print(f'func {func.__name__} cost time:{time.perf_counter() - t:.8f} s')
        return result

    if iscoroutinefunction(func):
        return func_async
    else:
        return fun


@cost_time
def test():
    print('func start')
    time.sleep(2)
    print('func end')


@cost_time
async def test_async():
    print('async func start')
    await asyncio.sleep(2)
    print('async func end')


if __name__ == '__main__':
    test()
    asyncio.get_event_loop().run_until_complete(test_async())

使用裝飾器來統(tǒng)計函數(shù)執(zhí)行耗時的好處是對函數(shù)的入侵性小,易于編寫和修改。

裝飾器裝飾函數(shù)的方案只適用于統(tǒng)計函數(shù)的運行耗時,如果有代碼塊耗時統(tǒng)計的需求就不能用了,這種情況下我們可以使用 with 語句自動管理上下文。

5. with 語句統(tǒng)計運行耗時

通過實現(xiàn) enter 和 exit 函數(shù)可以讓我們在進入上下文和退出上下文時進行一些自定義動作,例如連接 / 斷開數(shù)據(jù)庫、打開 / 關(guān)閉文件、記錄開始 / 結(jié)束時間等等,這里我們用來統(tǒng)計函數(shù)塊的執(zhí)行時間。

import asyncio
import time


class CostTime(object):
    def __init__(self):
        self.t = 0

    def __enter__(self):
        self.t = time.perf_counter()
        return self

    def __exit__(self, exc_type, exc_val, exc_tb):
        print(f'cost time:{time.perf_counter() - self.t:.8f} s')


def test():
    print('func start')
    with CostTime():
        time.sleep(2)
        print('func end')


async def test_async():
    print('async func start')
    with CostTime():
        await asyncio.sleep(2)
        print('async func end')


if __name__ == '__main__':
    test()
    asyncio.get_event_loop().run_until_complete(test_async())

with 語句不僅可以統(tǒng)計代碼塊的執(zhí)行時間,也可以統(tǒng)計函數(shù)的執(zhí)行時間,還可以統(tǒng)計多個函數(shù)的執(zhí)行時間之和,相比裝飾器來說對代碼的入侵性比較大,不易于修改,好處是使用起來比較靈活,不用寫過多的重復(fù)代碼。

6.延展:python實現(xiàn)函數(shù)超時退出

方法一

import time
import eventlet#導(dǎo)入eventlet這個模塊
eventlet.monkey_patch()#必須加這條代碼
with eventlet.Timeout(5,False):#設(shè)置超時時間為2秒
  time.sleep(4)
  print('沒有跳過這條輸出')
print('跳過了輸出')

第二個方法 不太會用,用的不成功,不如第一個

import time
import timeout_decorator

@timeout_decorator.timeout(5)
def mytest():
    print("Start")
    for i in range(1,10):
        time.sleep(1)
        print("{} seconds have passed".format(i))

if __name__ == '__main__':
    mytest()

Python設(shè)置函數(shù)調(diào)用超時

import time
import signal
def test(i):
time.sleep(i%4)
print "%d within time"%(i)
return i
if __name__ == '__main__':
def handler(signum, frame):
raise AssertionError
i = 0
for i in range(1,10):
try:
signal.signal(signal.SIGALRM, handler)
signal.alarm(3)
test(i)
i = i + 1
signal.alarm(0)
except AssertionError:
print "%d timeout"%(i)

說明:

1、調(diào)用test函數(shù)超時監(jiān)控,使用sleep模擬函數(shù)執(zhí)行超時

2、引入signal模塊,設(shè)置handler捕獲超時信息,返回斷言錯誤

3、alarm(3),設(shè)置3秒鬧鐘,函數(shù)調(diào)用超時3秒則直接返回

4、捕獲異常,打印超時信息

執(zhí)行結(jié)果

within time
within time
timeout
within time
within time
within time
timeout
within time
within time

到此這篇關(guān)于Python中計算函數(shù)執(zhí)行時間的五種方法的文章就介紹到這了,更多相關(guān)Python計算函數(shù)執(zhí)行時間內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

  • Python爬蟲爬取糗事百科段子實例分享

    Python爬蟲爬取糗事百科段子實例分享

    在本篇文章里小編給大家整理了關(guān)于Python爬蟲爬取糗事百科段子實例內(nèi)容,需要的朋友們可以參考下。
    2020-07-07
  • python運行cmd命令10種方式并獲得返回值的高級技巧

    python運行cmd命令10種方式并獲得返回值的高級技巧

    這篇文章主要給大家介紹了關(guān)于python運行cmd命令10種方式并獲得返回值的高級技巧,主要包括python腳本執(zhí)行CMD命令并返回結(jié)果的例子使用實例、應(yīng)用技巧,文中通過代碼介紹的非常詳細,需要的朋友可以參考下
    2024-03-03
  • 回歸預(yù)測分析python數(shù)據(jù)化運營線性回歸總結(jié)

    回歸預(yù)測分析python數(shù)據(jù)化運營線性回歸總結(jié)

    本文主要介紹了python數(shù)據(jù)化運營中的線性回歸一般應(yīng)用場景,常用方法,回歸實現(xiàn),回歸評估指標,效果可視化等,并采用了回歸預(yù)測分析的數(shù)據(jù)預(yù)測方法
    2021-08-08
  • 一文詳解Python中的時間和日期處理

    一文詳解Python中的時間和日期處理

    在Python開發(fā)中,我們經(jīng)常需要處理日期和時間,Python提供了一些內(nèi)置模塊,如datetime、time和calendar,這些模塊讓我們能夠輕松地獲取、操作和格式化日期和時間,本文將介紹如何在Python中使用這些模塊進行日期和時間的處理
    2023-06-06
  • python經(jīng)典百題之畫圓形多種解決辦法

    python經(jīng)典百題之畫圓形多種解決辦法

    在Python中,您可以使用各種庫和工具來繪制圖形,其中包括繪制圓形,下面這篇文章主要給大家介紹了關(guān)于python經(jīng)典百題之畫圓形的多種解決辦法,文中通過代碼介紹的非常詳細,需要的朋友可以參考下
    2024-03-03
  • 實例解析Python中的__new__特殊方法

    實例解析Python中的__new__特殊方法

    __new__方法在Python中用于被創(chuàng)建類實例,接下來我們以實例解析Python中的__new__特殊方法,注意一下__new__與__init__方法的區(qū)別
    2016-06-06
  • OpenCV+face++實現(xiàn)實時人臉識別解鎖功能

    OpenCV+face++實現(xiàn)實時人臉識別解鎖功能

    這篇文章主要為大家詳細介紹了OpenCV+face++實現(xiàn)實時人臉識別解鎖功能,具有一定的參考價值,感興趣的小伙伴們可以參考一下
    2019-08-08
  • Ubuntu中安裝指定Python版本方法詳解(理論上各版本通用)

    Ubuntu中安裝指定Python版本方法詳解(理論上各版本通用)

    現(xiàn)在基于linux的發(fā)行版本有很多,有centos,ubuntu等,一般基于linux的衍生系統(tǒng)至少都安裝了Python2版本,但是現(xiàn)在Python已經(jīng)是3.x版本大行其道了,這篇文章主要給大家介紹了關(guān)于Ubuntu中安裝指定Python版本方法的相關(guān)資料,理論上各版本通用,需要的朋友可以參考下
    2023-06-06
  • Python簡直是萬能的,這5大主要用途你一定要知道?。ㄍ扑])

    Python簡直是萬能的,這5大主要用途你一定要知道?。ㄍ扑])

    這篇文章主要介紹了Python主要用途,文中通過示例代碼介紹的非常詳細,對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧
    2019-04-04
  • python實現(xiàn)炫酷屏幕保護的示例代碼

    python實現(xiàn)炫酷屏幕保護的示例代碼

    這篇文章主要為大家詳細介紹了如何利用python實現(xiàn)炫酷屏幕保護效果,文中的示例代碼講解詳細,具有一定的學(xué)習(xí)價值,感興趣的小伙伴可以跟隨小編一起了解一下
    2023-12-12

最新評論

长沙市| 奉节县| 敖汉旗| 博客| 曲阜市| 乐清市| 绵竹市| 蒙阴县| 前郭尔| 台山市| 英超| 新乐市| 包头市| 库伦旗| 滦南县| 肃北| 大田县| 大渡口区| 建始县| 博湖县| 牡丹江市| 开鲁县| 泽库县| 鹿泉市| 华池县| 武乡县| 平果县| 道孚县| 平原县| 宁城县| 射洪县| 金沙县| 新野县| 牟定县| 合作市| 宝兴县| 车致| 探索| 淮滨县| 静宁县| 陇南市|