测量包含的代码块时钟墙时间的定时器上下文管理器。
项目描述
contexttimer 为您提供了一些实用工具,可以快速测量代码块或函数的执行时间。
定时器作为上下文管理器
contexttimer.Timer 是一个上下文管理器,用于测量它包含的代码块的执行时间。通过 elapsed 属性可以访问经过的时间。
>>> with Timer() as t: ... # some code here >>> print t.elapsed # a value in seconds
contexttimer.Timer 上下文管理器
contexttimer.Timer 是一个带有2个参数和公共属性的 上下文管理器
default_timer:特定平台的计时器函数(Unix平台的 time.time 和Windows平台的 time.clock)。您可以通过将计时器传递给构造函数来实例化一个 Timer 对象。
factor:应用于 elapsed 属性的乘数因子。例如,1000的因子将导致 elapsed 以毫秒而不是秒为单位表示。默认值为1。
elapsed: (只读属性) 代码块执行的时间墙时钟计时,以秒为单位。默认情况下,以秒为单位表示。
示例
>>> from contexttimer import Timer >>> with Timer(factor=1000) as t: ... for i in xrange(10000000): ... pass ... >>> print(t.elapsed) 73.6618041992 # in miliseconds
请注意,elapsed 是按需计算的,因此可以测量代码块的子部分。
>>> with Timer(factor=1000) as t: ... # do some things ... print t.elapsed ... # do other tings ... print t.elapsed ... 10.122 # in ms 20.567
contexttimer.timer 函数装饰器
您可以使用 @timer 函数装饰器来测量整个函数的执行时间。当函数返回其值时,其执行时间将打印到 stdout(默认)或日志记录器。
示例
>>> @timer ... def sleep_for_2s(): ... time.sleep(2)
>>> sleep_for_2s() function sleep_for_2s execution time: 2.002
>>> logging.basicConfig() >>> @timer(logger=logging.getLogger()) ... def sleep_for_2s(): ... time.sleep(2)
>>> sleep_for_2s() DEBUG:root:function blah execution time: 2.002
因为它在内部使用了 Timer 上下文管理器,所以传递给 @timer 装饰器的所有参数都将用作 Timer 的初始化参数。
示例
>>> @timer(factor=1000) ... def sleepawhile(n): ... time.sleep(n) ... >>> sleepawhile(2) function sleepawhile execution time: 2000.089
contexttimer.timeout.timeout 装饰器
您可以使用 @timeout 函数装饰器来停止函数/方法调用,并在调用超过固定时间时调用处理程序。
示例
>>> def timeout_handler(limit, f, *args, **kwargs): ... print "{func} call timed out after {lim}s.".format( ... func=f.__name__, lim=limit) ... >>> @timeout(limit=5, handler=timeout_handler) ... def work(foo, bar, baz="spam") ... time.sleep(10) >>> work("foo", "bar", "baz") # time passes... work call timed out after 5s. >>>
感谢
感谢 halloi、wolanko 和 Jon Blackburn 他们的有益见解和贡献。
许可证
contexttimer 在 GPLv3 许可下发布。
项目详情
关闭
contexttimer-0.3.3.tar.gz 的哈希值
算法 | 哈希摘要 | |
---|---|---|
SHA256 | 35a1efd389af3f1ca509f33ff23e17d98b66c8fde5ba2a4eb8a8b7fa456598a5 |
|
MD5 | dfeb413be43d88e287687036cdb3a71e |
|
BLAKE2b-256 | 1de0504aa08a83dc2ff90f61a83b5f70d689e1f5138ab30576124ea2ff9f5076 |