python process takes 100% CPU

后端 未结 2 1362
忘掉有多难
忘掉有多难 2021-02-10 02:28

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():

    p         


        
相关标签:
2条回答
  • 2021-02-10 03:09

    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.

    0 讨论(0)
  • 2021-02-10 03:17

    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.

    0 讨论(0)
提交回复
热议问题