跳转到主要内容

测量包含的代码块时钟墙时间的定时器上下文管理器。

项目描述

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 (4.9 kB 查看哈希值)

上传时间

由支持

AWSAWS云计算和安全赞助商DatadogDatadog监控FastlyFastlyCDNGoogleGoogle下载分析MicrosoftMicrosoftPSF赞助商PingdomPingdom监控SentrySentry错误日志StatusPageStatusPage状态页面