Efficient and fast Python While loop while using sleep()

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.

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)