5

I am trying to run python application and execute actions based on specified interval. Below code is consuming constantly 100% of CPU.

def action_print():

    print "hello there"

interval = 5
next_run = 0

while True:

    while next_run > time.time():
        pass

    next_run = time.time() + interval

    action_print()

I would like to avoid putting process to sleep as there will be more actions to execute at various intervals.

please advise

m1k3y3
  • 2,762
  • 8
  • 39
  • 68
  • 2
    If you don't want to sleep one way or another, you'll burn CPU. – Mat Feb 19 '12 at 13:32
  • Could you elaborate on "there will be more actions to execute at various intervals"? – Fred Foo Feb 19 '12 at 13:34
  • how can I make sure everything gets executed on-time while process is sleeping? I tried to use sleep however anything that is less than a second eats up the cpu. – m1k3y3 Feb 19 '12 at 13:35
  • Do you want this process to take 100% cpu? – lpostula Feb 19 '12 at 13:35
  • @larsmans - i mean more actions are about to come not just print. whole problem is in intervals that are floats i.e. 3.5s, 4.73s etc. – m1k3y3 Feb 19 '12 at 13:38
  • @m1k3y02: compute the exact moments at which actions have to be undertaken, then sleep until that time. – Fred Foo Feb 19 '12 at 13:38
  • @kasmanit - I want to avoid high cpu consumption while it is waiting for new action, which may come all of a sudden – m1k3y3 Feb 19 '12 at 13:39

2 Answers2

16

If you know when the next run will be, you 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 to be able to interrupt you, use an event like 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 up yours.

In many cases, you will also want to use a Lock to avoid race conditions on shared data. Make sure to clear the event while you hold the lock.

You should also be aware that under cpython, only one thread can execute Python code. Therefore, if your program is CPU-bound over multiple threads and you're using cpython or pypy, you should substitute threading with multiprocessing.

phihag
  • 278,196
  • 72
  • 453
  • 469
2

Presumably you do not want to write time.sleep(interval) , but replacing 'pass' with time.sleep(0.1) will almost completely free up your CPU, and still allow you flexibility in the WHILE predicate.

Alternatively you could use a thread for each event you are scheduling and use time.sleep(interval) but this will still tie up your CPU.

Bottom line : your loop WHILE : PASS is going round and round very fast consuming all your CPU.

user1202733
  • 623
  • 4
  • 10