0

If I have a function like this:

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?

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.

UPDATE: Note I'm not interested in writing a timer as a decorator in the function, or running something from the command line. 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". This is not what I'm looking to do.

user12282936
  • 167
  • 2
  • 7

1 Answers1

1

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. Wrap the call in a lambda or function instead:

timeit(lambda: func(*args, **kwargs), number)
Mad Physicist
  • 107,652
  • 25
  • 181
  • 264