如何将 *args 传递给我的 timeit.Timer 对象?
我最初为计时函数制作了一个自定义函数,如下所示:
def timefunc(function, *args):
start = time.time()
data = function(*args)
end = time.time()
time_taken = end - start
print "Function: "+function.__name__
print "Time taken:",time_taken
return data
现在,在了解了 timeit 模块后,我想使用它来实现相同的功能。我只是不知道如何在向其发送函数和 *args 参数时执行此操作。我已经发现我必须在 setup arg 中执行此操作:
"from __main__ import function"
但是我不知道如何处理 *args,因为 'stmt' 和 'setup' 参数都是字符串,我如何传递变量?
I originally made a custom function for timing functions that looks like this:
def timefunc(function, *args):
start = time.time()
data = function(*args)
end = time.time()
time_taken = end - start
print "Function: "+function.__name__
print "Time taken:",time_taken
return data
Now, having learned about the timeit module, I want to implement the same thing using that. I just can't figure out how to do it while sending it the function and *args arguments. I have already figured out that I have to do this in the setup arg:
"from __main__ import function"
But I can't figure out what to do about *args, since both the 'stmt' and 'setup' arguments are strings, how can I pass the variables?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
从 Python 2.6 开始,
timeit
模块除了字符串之外还接受可调用的stmt
。考虑到这一点,你可以这样做:Starting with Python 2.6 the
timeit
module besides a string also accepts a callable asstmt
. With that in mind you can do this: