使用 sleep() 时高效快速的 Python While 循环 [英] Efficient and fast Python While loop while using sleep()
问题描述
我正在尝试使用 Pyserial 通过串行方式与设备进行通信.由于命令需要不断发送,因此必须将它们放在 Python 中的 while 循环中.
I am attempting to communicate with a device over serial using Pyserial. As commands need to be continually sent, they have to be placed in a while loop in Python.
我目前正在使用此代码,并查看了 python 进程占用 100% CPU:
I am currently using this code, and have taken a look at python process takes 100% CPU:
while True:
#do some serial sending here
time.sleep(0.2)
此代码有效.但是,发送速度很慢.我试图通过减少 sleep
间隔来使其更快,但它似乎对 CPU 的负载有点过大.
This code works. However, the sending speed is slow. I tried to make it faster by decreasing the sleep
interval, but it seems to load the CPU a bit too much.
简而言之,有没有什么方法可以有效地永远迭代一个 while 循环,同时仍然保持低 CPU 资源消耗?
In short, is there a any way to effectively iterate over a while loop forever, while still maintaining a low consumption of CPU resources?
推荐答案
CPU 浪费缓慢的部分是执行串行发送".只有短暂睡眠的 while 循环将使用可忽略不计的 CPU.
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.
在这个相当慢的 CPU 上,我看到了这个:
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
我在解释器中运行它们并用 ctrl-C 停止每个 while 循环.
I ran those in the interpreter and stopped each while loop with ctrl-C.
这篇关于使用 sleep() 时高效快速的 Python While 循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!