CKTIS / Python
timeit.timeit
Measures the elapsed time for a specified number of repetitions.
Version: Python 3.14; repository image, production runtime not attested
Syntax
timeit.timeit(stmt='pass', setup='pass', timer=timeit.default_timer, number=1000000, globals=None)Measures the elapsed time for a specified number of repetitions.
The returned duration covers all repetitions, not one call. Count effects explicitly and avoid asserting an exact wall-clock duration.
With the default perf_counter clock the result is total elapsed seconds as a float. Divide by number for a per-execution average when number is positive. A string can use the globals dictionary, or pass a zero-argument callable. Setup is excluded and cyclic garbage collection is temporarily disabled by default. Four calls append four items. The API defaults to number=1_000_000, whereas python -m timeit without -n selects a loop count automatically. Set up with gc.enable() to include cyclic collection. When timing disables a previously enabled GC, it re-enables it even if the statement raises.
import timeit,gc
ticks=iter([1.,3.])
steps=[]
elapsed=timeit.timeit(lambda: steps.append(gc.isenabled()), lambda: steps.append('setup'), timer=lambda:next(ticks),number=3)
assert elapsed==2. and steps==['setup',False,False,False]
old=gc.isenabled()
try:
gc.enable()
def fail():
assert not gc.isenabled()
raise ValueError('timed')
try: timeit.timeit(fail,number=1)
except ValueError: pass
else: raise AssertionError
assert gc.isenabled()
seen=[]
timeit.timeit(lambda:seen.append(gc.isenabled()), setup=gc.enable,number=1)
assert seen==[True]
finally:
if not old: gc.disable()
Examples
import timeit
calls = []
elapsed = timeit.timeit(lambda: calls.append(1), number=4)
print(len(calls), elapsed >= 0)
Result
4 True
With the default perf_counter clock the result is total elapsed seconds as a float. Divide by number for a per-execution average when number is positive. A string can use the globals dictionary, or pass a zero-argument callable. Setup is excluded and cyclic garbage collection is temporarily disabled by default. Four calls append four items. The API defaults to number=1_000_000, whereas python -m timeit without -n selects a loop count automatically. Set up with gc.enable() to include cyclic collection. When timing disables a previously enabled GC, it re-enables it even if the statement raises.