python程序占用cpu过高_python进程占用100%的CPU

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

解决方案

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
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值