Skip to content

Commit

Permalink
[3.13] gh-125997: suggest efficient alternatives for time.sleep(0) (G…
Browse files Browse the repository at this point in the history
…H-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 <10796600+picnixz@users.noreply.github.com>
  • Loading branch information
miss-islington and picnixz authored Jan 18, 2025
1 parent c75894a commit fff334e
Show file tree
Hide file tree
Showing 2 changed files with 13 additions and 2 deletions.
4 changes: 3 additions & 1 deletion Doc/library/os.rst
Original file line number Diff line number Diff line change
Expand Up @@ -5358,6 +5358,8 @@ information, consult your Unix manpages.
The following scheduling policies are exposed if they are supported by the
operating system.

.. _os-scheduling-policy:

.. data:: SCHED_OTHER

The default scheduling policy.
Expand Down Expand Up @@ -5449,7 +5451,7 @@ operating system.

.. function:: sched_yield()

Voluntarily relinquish the CPU.
Voluntarily relinquish the CPU. See :manpage:`sched_yield(2)` for details.


.. function:: sched_setaffinity(pid, mask, /)
Expand Down
11 changes: 10 additions & 1 deletion Doc/library/time.rst
Original file line number Diff line number Diff line change
Expand Up @@ -385,6 +385,8 @@ Functions
The suspension time may be longer than requested by an arbitrary amount,
because of the scheduling of other activity in the system.

.. rubric:: Windows implementation

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

Unix implementation:
.. rubric:: Unix implementation

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

.. note::

To emulate a "no-op", use :keyword:`pass` instead of ``time.sleep(0)``.

To voluntarily relinquish the CPU, specify a real-time :ref:`scheduling
policy <os-scheduling-policy>` and use :func:`os.sched_yield` instead.

.. audit-event:: time.sleep secs

.. versionchanged:: 3.5
Expand Down

0 comments on commit fff334e

Please sign in to comment.