hadar hadar - 4 months ago 20
Python Question

Does time.sleep help the processor?

Recently I was surfing on Stack Overflow (Python) and saw this post where Aaron Hall claims that


constantly running while loops can consume a lot of processing power. Adding a sleep period (even only a second) can greatly reduce that usage.


Is it really true? And if so, how come? Does the same rule apply to other programming languages as well (i.e. C++)?

Answer

TL;DR If you are polling for an event that happens once a minute, you might want to not check every nano second.

Yes, it is really true. Sleeping in a thread does reduce the CPU usage of that thread. While a thread sleeps, it hardly consumes any CPU time.

Yes, this is true for largely any language as long as the sleeping is implemented using the OS native threading API.

To think about this intuitively, let us consider a simplified version of the program from the linked question:

while end_condition_expression:
    if time_based_condition_expression:
        do_something()

Now, let us simplify the world, and assume that the program is the only process running on the processor.

Let us also assume, that the time based condition is true once a minute. Let us also assume that executing end_condition_expression and time_based_condition_expression costs 10 nano seconds of cpu time.

How much cpu time will this consume within a minute? Exactly one minute == 60 000 000 000 nano seconds. The cpu usage will have been 100% during the entire time. The loop will have iterated six billion times.

Now, consider this variation of the program:

while end_condition_expression:
    if time_based_condition_expression:
        do_something()
    sleep_for_a_second()

How many times will the loop have executed within a minute? 60 iterations. How much cpu time will this consume within a minute? 60 * 10 ns = 600 ns. That is one hundred millionth of what the non-sleeping version of the program used.

In reality, there is a bit of overhead from the call to sleep, and the cpu time is shared with other processes, and a scheduler is involved, and the exact cpu usage won't exactly match my assumptions, but the idea stays the same.