Skip to content

gh-114665: Clarify that timeit setup runs once per timing call - #162944

Open
jnrahme wants to merge 1 commit into
python:mainfrom
jnrahme:gh-114665-clarify-timeit-setup
Open

jnrahme wants to merge 1 commit into
python:mainfrom
jnrahme:gh-114665-clarify-timeit-setup

Conversation

@jnrahme

@jnrahme jnrahme commented Dec 1, 2026 •

Copy link
Copy Markdown

The timeit docs said the setup statement "is executed only once at the beginning", and the -s / --setup help said it was "executed once initially". That doesn't match the code.

Timer.timeit() runs setup once, then times the statement. That part is right. But repeat() and autorange() call timeit() again for each trial, and the command-line tool uses both (autorange when -n is omitted, then repeat with a default of 5). So setup usually runs many times, not once at the start. That is why this check fails:

python -m timeit --setup 'import sys; assert "csv" not in sys.modules' 'import csv'

import csv from an earlier trial is already in sys.modules when setup runs again.

This updates:

  • Doc/library/timeit.rst: the Timer class, the timeit() method, the -s option, and the examples intro, so they describe the actual once-per-call behavior
  • the Timer.timeit docstring and the argparse help in Lib/timeit.py

No runtime behavior is changed.

Fixes #114665

I confirmed the old wording against the current timeit() / repeat() / autorange() / CLI code, ran ./python -m test test_timeit (44 tests, OK), and built Doc/library/timeit.rst with Sphinx. The new sentences show up in the HTML, and the only Sphinx warnings were from other pages that were not part of this partial docs build.

AI assistance: I used an AI coding agent to find the misleading wording, draft the edits, and run the tests and docs build. I reviewed the diff and checked it against the implementation.

The docs and CLI help said setup ran "once initially" or "only once at
the beginning". Setup actually runs once at the start of every
Timer.timeit() call, so repeat(), autorange(), and the command-line
interface run it more than once.

Assisted-by: Grok Bot
@read-the-docs-community

Copy link
Copy Markdown

📖 2 files modified


Preview · build overview · cpython-previews · built Dec. 1, 2026, 5:48 p.m. UTC

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

timeit setup is affected by test statement

1 participant