跳转到主要内容

Python代码计时器

项目描述

Timer

Python代码计时器,支持块和函数级别的计时

安装

pip install timer

使用

  1. 导入

    from timer import timer
    
  2. 不带括号的装饰

    @timer
    def func(): ...
    
  3. 带括号的装饰

    @timer()
    def func(): ...
    
  4. 带名称和时间单位的装饰

    @timer('function name', 's')
    def func(): ...
    
  5. 带关键字参数的装饰

    @timer(name='function name', unit='s')
    def func(): ...
    
  6. 无对象的块级

    with timer():
        ...
    
  7. 有对象的块级

    with timer() as t:
        ...
        print(t.elapse)
    

示例代码

import logging
import time

from timer import timer, get_timer

# default timer's logging level is logging.DEBUG
# so timer would print nothing if logging level is logging.INFO or higher
logging.basicConfig(level=logging.DEBUG)

# or you can change default timer's logging level
timer.set_level(logging.DEBUG)

# also you can get a timer with custom logging level with get_timer(level)
warning_timer = get_timer(logging.WARNING)


# explicit the timer's name and it's time unit
@timer('function:add', unit='s')
def add(a, b):
    time.sleep(.1)
    return a + b


# function name is timer's name for default
@timer
def sub(a, b):
    time.sleep(.1)
    return a - b


if __name__ == '__main__':
    # 'timer' would be timer's name by default
    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))

输出

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

特别感谢

@Krzysztof S

项目详情


下载文件

下载适用于您的平台的文件。如果您不确定选择哪个,请了解有关安装包的更多信息。

源分布

timer-0.3.0.tar.gz (7.4 kB 查看哈希值)

上传时间:

构建分布

timer-0.3.0-py3-none-any.whl (8.0 kB 查看哈希值)

上传于 Python 3

由...