Skip to content

Minor Performance Regression Initializing threading.Event #96349

@dgiger42

Description

@dgiger42

Bug report

In the main Python branch, creating a threading.Event is slightly slower than it was in 3.10:

I ran a simple benchmark on the main branch (built with --enable-optimizations):

../cpython/python -m pyperf timeit -s 'from threading import Event' 'e = Event()'
.....................
Mean +- std dev: 1.59 us +- 0.02 us

And on 3.10:

../cpython3.10/python -m pyperf timeit -s 'from threading import Event' 'e = Event()'
.....................
Mean +- std dev: 1.52 us +- 0.02 us

When initializing an Event, it creates a Condition via Condition(Lock()). The Condition's __init__() then has to catch 3 exceptions in these blocks:

try:
    self._release_save = lock._release_save
except AttributeError:
    pass
try:
    self._acquire_restore = lock._acquire_restore
except AttributeError:
    pass
try:
    self._is_owned = lock._is_owned
except AttributeError:
    pass

My understanding is that the new zero-cost exceptions make try/except blocks significantly faster when an exception isn't thrown, but don't help when the exception is actually thrown.

For Condition objects, I think it would likely be easy to avoid this minor slowdown by using hasattr() instead of the try/except blocks, and it would also be more concise.

Your environment

  • CPython versions tested on: 3.10, 3.12
  • Operating system and architecture: Ubuntu 20.04, x86_64

Metadata

Metadata

Assignees

No one assigned

    Labels

    performancePerformance or resource usagestdlibStandard Library Python modules in the Lib/ directory

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions