【问题标题】:How to Measure How Long Running a Code Chunk Takes如何测量运行代码块需要多长时间
【发布时间】:2020-09-22 04:29:11
【问题描述】:

我试图弄清楚如何将一些括号括在我已经编写的代码段周围,以替代多行 timeit 示例中的三重括号。

这很好用:

import timeit
stmt = """\
a = bunch * of
fancy = math ** operations
tada = function(a, fancy)
"""
print("seconds = ", timeit.timeit(stmt=stmt, number=1, setup="import numpy as np; import pandas as pd"))

来源:https://docs.python.org/3.10/library/timeit.html#examples

我不知道如何让这些三引号在我创建的自定义函数中发挥出色。

但我想把它精简成这样:

fancy_timing_function(
a = bunch * of
fancy = math ** operations
tada = function(a, fancy)
)

输出是不错的3 minutes 21.40 seconds

感谢社区提供的任何帮助、建议或替代解决方案(也许有人已经想到了类似的东西)。提前致谢。

【问题讨论】:

标签: python benchmarking timing


【解决方案1】:

您可以像这样定义和使用上下文管理器:

import time
from contextlib import contextmanager

@contextmanager
def Timer(*args, **kwds):
    start = time.time()
    r = []
    try:
        yield r
    finally:
        r.append(time.time() - start)

with Timer() as t1:
    # Code to be wrapped and timed
    print("x")
    print("y")
    print("z")

with Timer() as t2:
    # More code to be wrapped and timed
    print("xxxxxxxxxxx")

print('Time 1: ' + str(t1[0]))
print('Time 2: ' + str(t2[0]))

结果:

x
y
z
xxxxxxxxxxx
Time 1: 2.6702880859375e-05
Time 2: 4.291534423828125e-06

【讨论】:

    猜你喜欢
    • 2012-07-06
    • 2019-03-03
    • 1970-01-01
    • 2011-02-20
    • 1970-01-01
    • 2011-11-11
    • 2014-04-21
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多