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.
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)
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.
In short, is there a any way to effectively iterate over a while loop forever, while still maintaining a low consumption of CPU resources?
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:
Now do some extra work in the loop:
I ran those in the interpreter and stopped each while loop with ctrl-C.