Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / Python

timeit.Timer

Stores a timing statement and setup operation for repeated measurements with the same configuration.

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

Syntax

timeit.Timer(stmt='pass', setup='pass', timer=timeit.default_timer, globals=None)

Stores a timing statement and setup operation for repeated measurements with the same configuration.

Setup runs once for each timing experiment and is excluded from its measured statement loop.

The constructor accepts statement and setup as strings or zero-argument callables and can share a globals dictionary with snippets. timeit(number) executes setup once before timing even for zero iterations. repeat runs independent timing loops with fresh setup calls. autorange tries 1, 2, 5, 10, … iterations until a trial lasts at least 0.2 seconds. autorange(callback) invokes callback(number, time_taken) after each trial including the successful one. Its return value is that final (number, time_taken) pair, for example (2, 0.3) after trials (1, 0.1) and (2, 0.3).

import timeit
events=[]
timer=timeit.Timer("events.append('run')","events.append('setup')",globals={'events':events})
timer.timeit(0)
assert events==['setup']
timer.repeat(repeat=2,number=1)
assert events==['setup','setup','run','setup','run']
ticks=iter([0.,0.1,0.,0.3])
runs=[]
assert timeit.Timer(lambda:runs.append(1), timer=lambda:next(ticks)).autorange()==(2,0.3)
assert len(runs)==3
ticks=iter([0.,0.1,0.,0.3])
samples=[]
pair=timeit.Timer('pass',timer=lambda:next(ticks)).autorange(lambda n,t:samples.append((n,t)))
assert samples==[(1,0.1),(2,0.3)] and pair==samples[-1]

Examples

import timeit
events = []
timer = timeit.Timer(lambda: events.append("run"), setup=lambda: events.append("setup"))
timer.timeit(number=2)
print(events)

Result

['setup', 'run', 'run']

The constructor accepts statement and setup as strings or zero-argument callables and can share a globals dictionary with snippets. timeit(number) executes setup once before timing even for zero iterations. repeat runs independent timing loops with fresh setup calls. autorange tries 1, 2, 5, 10, … iterations until a trial lasts at least 0.2 seconds. autorange(callback) invokes callback(number, time_taken) after each trial including the successful one. Its return value is that final (number, time_taken) pair, for example (2, 0.3) after trials (1, 0.1) and (2, 0.3).

Sources