Efficient and fast Python While loop while using sleep()

怎甘沉沦 提交于 2019-12-02 18:00:17

The slow CPU wasting part is the "do serial sending". The while loop with just a short sleep will use negligible CPU.

Can you show the serial sending code. There may be a way to speed that up.

On this rather slow CPU I see this:

import time
while True: time.sleep(0.2)      # 0% CPU
while True: time.sleep(0.02)     # 0% CPU
while True: time.sleep(0.002)    # 0.5% CPU
while True: time.sleep(0.0002)   # 6% CPU
while True: time.sleep(0.00002)  # 18% CPU

Now do some extra work in the loop:

import time
while True: range(10000) and None; time.sleep(0.2)      # 1% CPU
while True: range(10000) and None; time.sleep(0.02)     # 15% CPU
while True: range(10000) and None; time.sleep(0.002)    # 60% CPU
while True: range(10000) and None; time.sleep(0.0002)   # 86% CPU

I ran those in the interpreter and stopped each while loop with ctrl-C.

In regards to your comment on Joachim's answer:

Then your microcontroller code needs a redesign. Otherwise you're just turning you general-purpose computer into nothing more than a dumb "microcontroller" that iterates over unneeded code repeatedly, hence the 100% cpu. Another symptom of you using your computer incorrectly is the fact that your hardware motor's speed depends on the speed at which you send commands to it via the serial interface. You need to "command" it with the computer which will host your high-level logic. And your micro-controller needs to handle the low-level, repetative control of the motor.

You have to figure out the tradeoff you are willing to have between speed and CPU load.

If you have to send short bursts of data, while not doing so much between messages, then maybe you can live with high CPU load for a short time as the average might still be low.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!