[ACCEPTED]-python process takes 100% CPU-consumption
If you know when the next run will be, you 11 can simply use time.sleep
:
import time
interval = 5
next_run = 0
while True:
time.sleep(max(0, next_run - time.time()))
next_run = time.time() + interval
action_print()
If you want other threads 10 to be able to interrupt you, use an event like 9 this:
import time,threading
interval = 5
next_run = 0
interruptEvent = threading.Event()
while True:
interruptEvent.wait(max(0, next_run - time.time()))
interruptEvent.clear()
next_run = time.time() + interval
action_print()
Another thread can now call interruptEvent.set()
to wake 8 up yours.
In many cases, you will also want 7 to use a Lock to avoid race conditions on shared data. Make 6 sure to clear the event while you hold the 5 lock.
You should also be aware that under 4 cpython, only one thread can execute Python 3 code. Therefore, if your program is CPU-bound 2 over multiple threads and you're using cpython 1 or pypy, you should substitute threading
with multiprocessing
.
Presumably you do not want to write time.sleep(interval) , but 9 replacing 'pass' with time.sleep(0.1) will 8 almost completely free up your CPU, and 7 still allow you flexibility in the WHILE 6 predicate.
Alternatively you could use a 5 thread for each event you are scheduling 4 and use time.sleep(interval) but this will 3 still tie up your CPU.
Bottom line : your 2 loop WHILE : PASS is going round and 1 round very fast consuming all your CPU.
More Related questions
We use cookies to improve the performance of the site. By staying on our site, you agree to the terms of use of cookies.