程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式師世界 >> 編程語言 >  >> 更多編程語言 >> Python

Python implements timer and counts the running time

編輯:Python

We implement timers in two ways .

  • Decorator implements timer
  • The generator implements timers

Decorator implements timer

import time
def timer_dec(func):
def inner(*args, **kwargs):
start = time.time()
ret_val = func(*args, **kwargs)
end = time.time()
print(f'pay time is {end-start} s')
return ret_val
return inner
@timer_dec
def haha():
print(' drowned in laughter. ')
time.sleep(0.01)
haha()

Output results

 drowned in laughter.
pay time is 0.010136842727661133 s

The generator implements timers

Use the generator to realize , Need help Python Built in Library contextlib help .

It doesn't mean that we have to resort to contextlib, It's about using contextlib Can be more elegant
You can refer to : Shallow python in with Usage of , Context manager
from contextlib import contextmanager
def haha():
print(' drowned in laughter. ')
time.sleep(0.01)
@contextmanager
def timer_gen():
start = time.time()
yield
end = time.time()
print(f'pay time is {end-start} s')
with timer_gen():
haha()

Output results

 drowned in laughter.
pay time is 0.010103464126586914 s

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式師世界 All Rights Reserved