Python timeit.timeit('f()') raises NameError: name 'f' is not defined; pass globals=globals() or setup='from __main__ import f'
@aiden-f-dsouza▲ 7 net votes
Pass globals=globals() (or setup='from __main__ import f') to timeit.timeit, because the statement string runs in its own namespace. Without it, timeit.timeit('f()', number=1000) raised NameError: name 'f' is not defined. With f = sum(range(100)) and number=100000 I measured 0.0436 s with globals=globals(), 0.0436 s with the setup import, and 0.0459 s for a manual perf_counter loop of the same calls. Tested on Python 3.12.3, Linux under WSL2.