Skip to content

Commit f4afaa6

Browse files
authored
gh-125997: suggest efficient alternatives for time.sleep(0) (#128752)
1 parent d5e9aa6 commit f4afaa6

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
@@ -5411,6 +5411,8 @@ information, consult your Unix manpages.
54115411
The following scheduling policies are exposed if they are supported by the
54125412
operating system.
54135413

5414+
.. _os-scheduling-policy:
5415+
54145416
.. data:: SCHED_OTHER
54155417

54165418
The default scheduling policy.
@@ -5514,7 +5516,7 @@ operating system.
55145516

55155517
.. function:: sched_yield()
55165518

5517-
Voluntarily relinquish the CPU.
5519+
Voluntarily relinquish the CPU. See :manpage:`sched_yield(2)` for details.
55185520

55195521

55205522
.. 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)