gh-125997: suggest efficient alternatives for time.sleep(0)#128752
Conversation
The implementation of `time.sleep()` changed in Python 3.11 and relies on `clock_nanosleep()` or `nanosleep()` since then. This introduced a regression in code using `time.sleep(0)` for a syscall "no-op", polling or momentarily suspending the caller's thread. To alleviate the performance regression, we suggest some alternatives depending on the caller's needs.
|
@hauntsaninja and @charles-cooper: I would appreciate if you can share your thoughts on those suggestions as you were also involved in the other PR's discussion. |
Sorry, something went wrong.
|
i think it's interesting that besides that, i would just mention that clock_nanosleep may sleep at least 50us on linux. (i mean this is arguably a linux bug, but it is kind of surprising to users that sleep(0) sleeps a lot longer than one might expect). |
Sorry, something went wrong.
Actually,
While it's mentioned like that, I think it's wrong in the first place to rely on Another solution is to check if we're on FreeBSD or not, but this makes maintainance harder. Also, for those reading the PR only, the sleep gap only happens at t = 0 and not at t = 1e-9 (for t = 1e-9, |
Sorry, something went wrong.
There was a problem hiding this comment.
Thanks, this PR looks great, I think this is right approach.
I would not document current implementation choices of default Linux scheduler, especially since we've currently only had one report in >2 years. (If it does come up again, we can mention os.sched_setscheduler / PR_SET_TIMERSLACK)
Sorry, something went wrong.
vstinner
left a comment
There was a problem hiding this comment.
LGTM
Sorry, something went wrong.
|
@vstinner I plan to merge this PR with no commit message and the current PR title. I don't want to expand more on the rationale in the commit and I think it's better to look at the issue directly. WDYT? |
Sorry, something went wrong.
vstinner
left a comment
There was a problem hiding this comment.
LGTM. Go ahead.
Sorry, something went wrong.
|
Thanks @picnixz for the PR 🌮🎉.. I'm working now to backport this PR to: 3.13. |
Sorry, something went wrong.
|
Thanks @picnixz for the PR 🌮🎉.. I'm working now to backport this PR to: 3.12. |
Sorry, something went wrong.
…ythonGH-128752) (cherry picked from commit f4afaa6) Co-authored-by: Bénédikt Tran <10796600+picnixz@users.noreply.github.com>
|
Sorry, @picnixz, I could not cleanly backport this to |
Sorry, something went wrong.
After a discussion with Victor and because #128274 is not convincing enough, we decide to:
time.sleep(), andtime.sleep(0).See #125997 (comment) for more details.
time.sleep(0)is slower on Python 3.11 than on Python 3.10 #125997📚 Documentation preview 📚: https://cpython-previews--128752.org.readthedocs.build/