使用100%cpu的相对简单的Python脚本 [英] Relatively simple Python script using 100% cpu

查看:122
本文介绍了使用100%cpu的相对简单的Python脚本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我将不提供代码,因为它太长了。 python脚本涉及执行while循环中运行的大量命令。

I'm not going to provide the code because it's too long. The python script involves executing a lengthy number of commands run in a while loop.

基本结构

while True:
    The meat goes here
    with the odd if:
        and stuff

现在我完成了它,我注意到它在运行时会使用100%CPU,没有例外。我是一个初学者,真的不知道该问题的起因。我以为是因为脚本可以无限期地运行(直到我手动退出它),如果它每秒重复执行多次循环,则可能只是在给CPU增加负担。我在一段时间的底部添加了time.sleep(1),以查看是否是没有任何改善的问题。

Now that I'm finished it, I'm noticing that upon running it, it uses 100% CPU, no exceptions. I'm a beginner and don't really know what to attribute this issue to. I thought that maybe because the script runs indefinitely (until I exit it manually) it might just be taxing on the CPU if it's repeating the loop a number of times a second. I added time.sleep(1) at the bottom of the while to see if that was the issue with no improvements.

有人有什么想法吗?这是一个很长的事件序列,但是它们很大程度上取决于一个if语句,它不会经常触发。 100%的CPU使用率在该特定if语句被触发之前就已经发生了,所以我真的很茫然。

Anyone have any ideas? It is quite a long sequence of events, but they are heavily dependent on an if statement which isn't triggered all that often. The 100% CPU usage occurs before that particular if statement is even triggered, so I'm really at a loss.

编辑:忘记包括它在Unix中运行环境(Debian)

forgot to include that it's running in a unix environment (Debian)

推荐答案

除非存在一些妨碍使用CPU的方式(例如,在磁盘上等待) IO或网络IO,或通过睡眠暂停执行),则在程序运行时,CPU使用率始终在100%左右。

Unless there is something to get in the way of the CPU being used (for example, waiting on disk IO or network IO, or pausing execution by sleeping), CPU usage will always be at around 100% while a program is running.

如果您不希望它一直使用100%CPU,则可能需要添加time.sleep(numberOfSeconds)到循环中只检查一遍又一遍的条件。

You might want to add in a time.sleep(numberOfSeconds) to your loop if you don't want it to be using 100% CPU all the time, if it's only checking for a certain condition over and over.

这篇关于使用100%cpu的相对简单的Python脚本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆