0

I tried doing timeit.timeit("func()") (func is a function defined by myself), however, I always get the error name 'func' is not defined. Using Jupyter Notebook (I know about the magic timeit of Jupyter, but I wonder why this doesn't work?).

2 Answers2

1

Most likely you are looking for (without quotes, just directly):

timeit.timeit(func, number=1000)

instead of

timeit.timeit("func()", number=1000)


To have parameters or other functions, use triple quotes, e.g.:
import timeit
import_module = "import whatever_module"
testcode = ''' 
def test():
    # some nasty operations here
    pass
'''
print(timeit.repeat(stmt=testcode, setup=import_module))

The code must be self-contained, no external references are allowed.

Jan
  • 42,290
  • 8
  • 54
  • 79
  • How can I pass a parameter that way? I would like to test how long the function takes to execute –  May 29 '20 at 15:31
0

If you want to use it with first argument a string, that string must contain your full code, e.g.:

s = """
def func(n=10000):
    return [x ** 2 for x in range(n)]


func(10000)
"""


timeit.timeit(s)

or you need to use the setup parameter:

s = """
def func(n=10000):
    return [x ** 2 for x in range(n)]
"""


timeit.timeit("func()", setup=s)
norok2
  • 25,683
  • 4
  • 73
  • 99