Does time.sleep help the processor?

I recently surfed in Qaru (Python) and saw this post where Aaron Hall claims that

constantly working, and cycles can consume more computing power. Adding a wait period (even for a second) can significantly reduce this usage.

It's true? And if so, how? Does the same rule apply to other programming languages ​​(e.g. C ++)?

+8
c ++ python
source share
1 answer

TL; DR If you are polling for an event that occurs once a minute, you may not check every second.

Yes this is true. Sleeping in a thread reduces CPU usage in that thread. While the thread is sleeping, it consumes almost no CPU time.

Yes, this is true for almost any language if hibernation is implemented using the OS’s native threading API.

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

while end_condition_expression: if time_based_condition_expression: do_something() 

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

Assume also that the temporary condition is true once per minute. Suppose also that running end_condition_expression and time_based_condition_expression costs 10 nano seconds of processor time.

How much time will the processor consume in a minute? Exactly one minute == 60,000,000,000 nano seconds . CPU utilization will be 100% at all times. The cycle will be repeated six billion times.

Now consider this version of the program:

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

How many cycles will be performed in a minute? 60 iterations. How much time will the processor consume in a minute? 60 * 10 ns = 600 ns . This amounts to one hundred millionth of what the non-singing version of the program used.

In fact, there is a bit of overhead from a dream call, and the processor time is shared by other processes and the scheduler is involved, and the exact processor usage will not exactly match my assumptions, but the idea remains the same.

+8
source share

All Articles