简体   繁体   English

time.sleep是否有助于处理器?

[英]Does time.sleep help the processor?

Recently I was surfing on Stack Overflow (Python) and saw this post where Aaron Hall claims that 最近我在Stack Overflow(Python)上冲浪,看到了Aaron Hall声称的这篇文章

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 (ie C++)? 同样的规则是否也适用于其他编程语言(即C ++)?

TL;DR If you are polling for an event that happens once a minute, you might want to not check every nano second. TL; DR如果您正在轮询每分钟发生一次的事件,您可能不想检查每纳秒。

Yes, it is really true. 是的,这是真的。 Sleeping in a thread does reduce the CPU usage of that thread. 在线程中休眠会降低该线程的CPU使用率。 While a thread sleeps, it hardly consumes any CPU time. 当线程休眠时,它几乎不消耗任何CPU时间。

Yes, this is true for largely any language as long as the sleeping is implemented using the OS native threading API. 是的,只要使用操作系统本机线程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. 我们还假设执行end_condition_expressiontime_based_condition_expression需要10纳秒的CPU时间。

How much cpu time will this consume within a minute? 一分钟内消耗多少CPU时间? Exactly one minute == 60 000 000 000 nano seconds . 恰好一分钟= = 60 000 000 000纳秒 The cpu usage will have been 100% during the entire time. 在整个时间内,cpu的使用率为100%。 The loop will have iterated six billion times. 循环将迭代60亿次。

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. 60次迭代。 How much cpu time will this consume within a minute? 一分钟内消耗多少CPU时间? 60 * 10 ns = 600 ns . 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. 实际上,从调用到睡眠有一些开销,并且cpu时间与其他进程共享,并且涉及调度程序,并且确切的cpu使用将不完全符合我的假设,但是这个想法保持不变。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM