how to pass parameters of a function when using timeit.Timer() how to pass parameters of a function when using timeit.Timer() python python

how to pass parameters of a function when using timeit.Timer()


The functions can use arguments in timeit if these are created using closures, we can add this behaviours by wrapping them in another function.

def foo(num1, num2):    def _foo():        # do something to num1 and num2        pass    return _fooA = 1B = 2import timeitt = timeit.Timer(foo(A,B))  print(t.timeit(5))

or shorter, we can use functools.partial instead of explicit closures declaration

def foo(num1, num2):    # do something to num1 and num2    passA = 1B = 2import timeit, functoolst = timeit.Timer(functools.partial(foo, A, B)) print(t.timeit(5))

EDIT using lambda, thanks @jupiterbjy

we can use lambda function without parameters instead of functools library

def foo(num1, num2):    # do something to num1 and num2    passA = 1B = 2import timeitt = timeit.Timer(lambda: foo(A, B)) print (t.timeit(5))


The code snippets must be self-contained - they cannot make external references. You must define your values in the statement-string or setup-string:

import timeitsetup = """A = 1B = 2def foo(num1, num2):    passdef mainprog():    global A,B    for i in range(20):        # do something to A and B        foo(A, B)"""t = timeit.Timer(stmt="mainprog()" setup=setup)print(t.timeit(5))

Better yet, rewrite your code to not use global values.


Supposing that your module filename is test.py

# some pre-defined constantsA = 1B = 2# function that does something criticaldef foo(n, m):    pass# main program.... do something to A and Bfor i in range(20):    passimport timeitt = timeit.Timer(stmt="test.foo(test.A, test.B)", setup="import test")  print t.timeit(5)