Timer
Python code timer, support block wise and function wise
Installation
pip install timer
Usage
-
import
from timer import timer
-
decorate without brackets
@timer
def func(): ...
-
decorate with brackets
@timer()
def func(): ...
-
decorate with name and time unit
@timer('function name', 's')
def func(): ...
-
decorate with key word arguments
@timer(name='function name', unit='s')
def func(): ...
-
block wise without object
with timer():
...
-
block wise with object
with timer() as t:
...
print(t.elapse)
Sample Code
import logging
import time
from timer import timer, get_timer
logging.basicConfig(level=logging.DEBUG)
timer.set_level(logging.DEBUG)
warning_timer = get_timer(logging.WARNING)
@timer('function:add', unit='s')
def add(a, b):
time.sleep(.1)
return a + b
@timer
def sub(a, b):
time.sleep(.1)
return a - b
if __name__ == '__main__':
with timer('time.sleep(2)') as t:
print(3)
time.sleep(1)
print(f'after time.sleep(1) once, t.elapse = {t.elapse}')
time.sleep(1)
print(f'after time.sleep(1) twice, t.elapse = {t.elapse}')
print(f'after with, t.elapse = {t.elapse}')
with warning_timer('test'):
pass
print(add(1, 1))
print(sub(2, 1))
Outputs
3
after time.sleep(1) once, t.elapse = 1.003798776
after time.sleep(1) twice, t.elapse = 2.0052743459999998
DEBUG:timer.time.sleep(2): 2.006 s
after with, t.elapse = 2.005628447
WARNING:timer.test:start
WARNING:timer.test:cost 0 ms
DEBUG:timer.function:add: 0.105 s
2
DEBUG:timer.sub: 102 ms
1
Special Thanks
@Krzysztof S