[英]Using timeit with args,kwargs
If I have a function like this:如果我有这样的 function:
def print_args(wait=0.4, *args, **kwargs):
print (f"Sleep: {wait}s")
time.sleep(wait)
print (f"Args: {args}")
print (f"Kwargs: {kwargs}")
>>> print_args(0.2, 2, k='a')
Sleep: 0.2s
Args: (2,)
Kwargs: {'k': 'a'}
How would I put the function print_args
into timeit
?我如何将 function print_args
放入timeit
?
This works:这有效:
>>> timeit(print_args, number=4)
But how to do:但是怎么做:
>>> timeit(print_args(0.2, 2, k='a', number=4)
Additionally, is there a generic way to do this something like:此外,是否有一种通用的方法来执行此操作,例如:
timeit(func(*args, **kwargs), number)
(And not just re-writing the above print_args
function but having something more generic for this pattern. (不仅仅是重写上面的print_args
function 而是对这种模式有更通用的东西。
UPDATE : Note I'm not interested in writing a timer as a decorator in the function, or running something from the command line.更新:请注意,我对在 function 中编写计时器作为装饰器或从命令行运行某些东西不感兴趣。 I am literally asking if it's possible to do something like this:我实际上是在问是否有可能做这样的事情:
timeit(func(*args, **kwargs), number)
If for whatever reason the mentioned duplicate addresses this directly, please tell me which answer does so.如果出于某种原因,提到的重复直接解决了这个问题,请告诉我哪个答案这样做。 The answers I've seen either suggest adding a timer or to use "IPython's %timeit
command".我看到的答案要么建议添加计时器,要么使用“IPython 的%timeit
命令”。 This is not what I'm looking to do.这不是我想要做的。
Unless the result of func(*args, **kwargs)
is the callable you want to time, timeit(func(*args, **kwargs), number)
is obviously not going to do what you want.除非func(*args, **kwargs)
的结果是你想要计时的可调用对象,否则timeit(func(*args, **kwargs), number)
显然不会做你想做的事。 Wrap the call in a lambda or function instead:将调用包装在 lambda 或 function 中:
timeit(lambda: func(*args, **kwargs), number)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.