Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / Python

Module timeit

Benchmark a small statement or callable in repeated batches.

Version: Python 3.14; repository image, production runtime not attested

Syntax

timeit.Timer(stmt, setup).repeat(repeat=3, number=2)

Benchmark a small statement or callable in repeated batches.

Setup runs once per timed batch outside the timed interval and number determines how many statement executions each batch contains. The repeat method returns the difference between timer readings per batch. The default timer measures seconds, while a custom timer determines its own units.

Garbage collection is disabled by default during timing and may be enabled explicitly in setup.

Examples

import timeit
counts = {"setup": 0, "stmt": 0}
def setup():
    counts["setup"] += 1
def statement():
    counts["stmt"] += 1
timer = timeit.Timer(statement, setup)
samples = timer.repeat(repeat=3, number=2)
print(len(samples), counts, all(t >= 0 for t in samples))
ticks = iter([10, 17, 30, 44])
custom = timeit.Timer(lambda: None, timer=lambda: next(ticks))
assert custom.repeat(repeat=2, number=1) == [7, 14]

Result

3 {'setup': 3, 'stmt': 6} True

Garbage collection is disabled by default during timing and may be enabled explicitly in setup.

Sources