如何解决如何衡量运行代码块所需的时间
我试图弄清楚如何用括号代替我在多行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
感谢社区中的任何帮助,建议或替代解决方案(也许有人已经想到了这种方法)。预先感谢。
解决方法
您可以定义和使用上下文管理器,如下所示:
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
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。