Skip to content

gh-137578: support top-level setup statements in Timer objects #137587

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 2 commits into
base: main
Choose a base branch
from
Open
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Prev Previous commit
Update timeit.py
- carry co_flags obtained from global setup
- update timeit() and repeat() functions
  • Loading branch information
picnixz authored Aug 9, 2025
commit 7f9cc56337de9ae99580d848ac121aa7029b125f
14 changes: 8 additions & 6 deletions Lib/timeit.py
Original file line number Diff line number Diff line change
Expand Up @@ -129,7 +129,7 @@ def __init__(self, stmt="pass", setup="pass", timer=default_timer,
raise ValueError("global_setup is neither a string nor callable")
if isinstance(setup, str):
# Check that the code can be compiled outside a function
compile(setup, dummy_src_name, "exec")
compile(setup, dummy_src_name, "exec", **compile_options)
stmtprefix = setup + '\n'
setup = reindent(setup, 4)
elif callable(setup):
Expand All @@ -141,7 +141,7 @@ def __init__(self, stmt="pass", setup="pass", timer=default_timer,
raise ValueError("setup is neither a string nor callable")
if isinstance(stmt, str):
# Check that the code can be compiled outside a function
compile(stmtprefix + stmt, dummy_src_name, "exec")
compile(stmtprefix + stmt, dummy_src_name, "exec", **compile_options)
stmt = reindent(stmt, 8)
elif callable(stmt):
local_ns['_stmt'] = stmt
Expand Down Expand Up @@ -252,15 +252,17 @@ def autorange(self, callback=None):


def timeit(stmt="pass", setup="pass", timer=default_timer,
number=default_number, globals=None):
number=default_number, globals=None,
*, global_setup="pass"):
"""Convenience function to create Timer object and call timeit method."""
return Timer(stmt, setup, timer, globals).timeit(number)
return Timer(stmt, setup, timer, globals, global_setup=global_setup).timeit(number)


def repeat(stmt="pass", setup="pass", timer=default_timer,
repeat=default_repeat, number=default_number, globals=None):
repeat=default_repeat, number=default_number, globals=None,
*, global_setup="pass"):
"""Convenience function to create Timer object and call repeat method."""
return Timer(stmt, setup, timer, globals).repeat(repeat, number)
return Timer(stmt, setup, timer, globals, global_setup=global_setup).repeat(repeat, number)


def main(args=None, *, _wrap_timer=None):
Expand Down
Loading