Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Efficient and fast Python While loop while using sleep()

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?

like image 881
jhtong Avatar asked Jun 07 '12 05:06

jhtong


People also ask

How do you sleep while looping in Python?

sleep() Python has built-in support for putting your program to sleep. The time module has a function sleep() that you can use to suspend execution of the calling thread for however many seconds you specify.

Which loop is faster in Python for while or do while?

In this case, the for loop is faster, but also more elegant compared to while. Please, have in mind that you can't apply list comprehensions in all cases when you need loops. Some more complex situations require the ordinary for or even while loops.

Which loop is more efficient in Python?

I think the answer here is a little more subtle than the other answers suggest, though the gist of it is correct: the for loop is faster because more of the operations happen in C and less in Python.


1 Answers

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.

like image 106
John La Rooy Avatar answered Sep 30 '22 05:09

John La Rooy