Skip to content

Commit fff334e

Browse files
[3.13] gh-125997: suggest efficient alternatives for time.sleep(0) (GH-128752) (#128984)
gh-125997: suggest efficient alternatives for `time.sleep(0)` (GH-128752) (cherry picked from commit f4afaa6) Co-authored-by: Bénédikt Tran <[email protected]>
1 parent c75894a commit fff334e

File tree

2 files changed

+13
-2
lines changed

2 files changed

+13
-2
lines changed

Doc/library/os.rst

+3-1
Original file line numberDiff line numberDiff line change
@@ -5358,6 +5358,8 @@ information, consult your Unix manpages.
53585358
The following scheduling policies are exposed if they are supported by the
53595359
operating system.
53605360

5361+
.. _os-scheduling-policy:
5362+
53615363
.. data:: SCHED_OTHER
53625364

53635365
The default scheduling policy.
@@ -5449,7 +5451,7 @@ operating system.
54495451

54505452
.. function:: sched_yield()
54515453

5452-
Voluntarily relinquish the CPU.
5454+
Voluntarily relinquish the CPU. See :manpage:`sched_yield(2)` for details.
54535455

54545456

54555457
.. function:: sched_setaffinity(pid, mask, /)

Doc/library/time.rst

+10-1
Original file line numberDiff line numberDiff line change
@@ -385,6 +385,8 @@ Functions
385385
The suspension time may be longer than requested by an arbitrary amount,
386386
because of the scheduling of other activity in the system.
387387

388+
.. rubric:: Windows implementation
389+
388390
On Windows, if *secs* is zero, the thread relinquishes the remainder of its
389391
time slice to any other thread that is ready to run. If there are no other
390392
threads ready to run, the function returns immediately, and the thread
@@ -393,12 +395,19 @@ Functions
393395
<https://learn.microsoft.com/windows-hardware/drivers/kernel/high-resolution-timers>`_
394396
which provides resolution of 100 nanoseconds. If *secs* is zero, ``Sleep(0)`` is used.
395397

396-
Unix implementation:
398+
.. rubric:: Unix implementation
397399

398400
* Use ``clock_nanosleep()`` if available (resolution: 1 nanosecond);
399401
* Or use ``nanosleep()`` if available (resolution: 1 nanosecond);
400402
* Or use ``select()`` (resolution: 1 microsecond).
401403

404+
.. note::
405+
406+
To emulate a "no-op", use :keyword:`pass` instead of ``time.sleep(0)``.
407+
408+
To voluntarily relinquish the CPU, specify a real-time :ref:`scheduling
409+
policy <os-scheduling-policy>` and use :func:`os.sched_yield` instead.
410+
402411
.. audit-event:: time.sleep secs
403412

404413
.. versionchanged:: 3.5

0 commit comments

Comments
 (0)