Skip to content

gh-151989: Add with timeout feature + re c module cooperative example#151990

Closed
zang-langyan wants to merge 1 commit into
python:mainfrom
zang-langyan:timeout
Closed

gh-151989: Add with timeout feature + re c module cooperative example#151990
zang-langyan wants to merge 1 commit into
python:mainfrom
zang-langyan:timeout

Conversation

@zang-langyan

@zang-langyan zang-langyan commented Jun 23, 2026

Copy link
Copy Markdown
Contributor

Usage Example:

>>> with timeout(0.2):
...     while True:
...         pass
...
Traceback (most recent call last):
  File "<python-input-1>", line 3, in <module>
    pass
TimeoutError: Timeout

>>> with timeout(0.2):
...     re.match(r"(a+)+b", "a" * 30 + "c")
...
Traceback (most recent call last):
  File "<python-input-2>", line 2, in <module>
    re.match(r"(a+)+b", "a" * 30 + "c")
    ~~~~~~~~^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File ".../cpython/Lib/re/__init__.py", line 166, in prefixmatch
    return _compile(pattern, flags).prefixmatch(string)
           ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~^^^^^^^^
TimeoutError: Timeout

Performance Summary
Tested on my Macbook Pro M4

  1. No extra overhead outside a timeout block (i.e. timeout_block == NULL timeout check is completely bypassed).
  2. Py_CheckTimeOut
  • fast path (with skip interval ≥ 8) takes 1.1~1.3ns per call;
  • slow path (with skip interval < 8) takes 2.0~6.3ns per call;
  • full calling (without skip interval) takes 10.2ns +- 1.2ns per call.
  1. re module integration
    By tapping into the existing signal‑check counter inside _sre, timeout checks add no measurable overhead to normal regexps while allowing catastrophic backtracking to be safely interrupted within the specified deadline.

@StanFromIreland

Copy link
Copy Markdown
Member

Closing as per issue.

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.

2 participants