all Python 3timeitfunction
timeit.timeit()
timing
Runs a code snippet number times and returns the total time in seconds, for benchmarking.
Syntax
timeit.timeit(stmt='pass', setup='pass', timer=default_timer, number=1000000, globals=None) -> float
The result is the total time for all runs, not one: the default number is 1,000,000, so timing slow code seems to hang. Code given as a string cannot see your variables; pass setup='from __main__ import f' or globals=globals(), or pass a zero-argument callable. Garbage collection is disabled while timing, so numbers can be more optimistic than reality.
Examples
import timeit
t = timeit.timeit('sum(range(100))', number=1000)
print(type(t).__name__) # → float
print(t) # → ? время зависит от машины
import timeit
data = list(range(100))
t = timeit.timeit('sorted(data)', globals={'data': data}, number=100)
print(t > 0) # → True
timeit.timeit('sorted(data)', number=1) # → NameError: name 'data' is not defined
See also
Common errors
Open in the full glossarydocs.python.orgReport an inaccuracy