Relatively simple Python script using 100% CPU

I will not provide the code because it is too long. Python script involves executing a large number of commands executed in a while loop.

Basic structure

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

      

Now that I'm done, I notice that it is using 100% CPU on startup, no exceptions. I'm a beginner and don't know what this refers to. I thought that maybe because the script is running indefinitely (until I exit it manually), it might just clothe the CPU if it repeats the loop a few times per second. I added time.sleep (1) at the bottom of the time to make sure this is a problem with no improvement.

Does anyone have any idea? It's a rather long sequence of events, but they rely heavily on the if statement, which doesn't run as often. 100% CPU usage happens before this if statement even fires, so I'm really at a loss.

Edit: forgot to include that it works in unix environment (Debian)

+2


source to share


5 answers


If there is anything that interferes with the CPU being used (such as waiting for disk I / O or network I / O, or suspending the execution of a hibernate), the CPU utilization will always be around 100% while the program is running.



You may need to add time.sleep (numberOfSeconds) to your loop if you don't want it to use 100% CPU all the time if it only checks a certain state over and over again.

+8


source


100% CPU means the script works well. I don't see any problem. If that prevents other programs from running, then run the script with a lower priority (with a good one)



+3


source


The question is why he shouldn't use 100%. This is the default for everything you write. In order not to use 100%, you need to have a special code that sits and waits for something. If you have it, then the error is in this code.

+2


source


Perhaps while

there is an break

or inside the loop continue

, so your code is being time.sleep(1)

skipped. Are you sure the part time.sleep(1)

is being fulfilled?

+1


source


The problem is that you don't have a sleep statement in your loop unless the if function is true, so your code loops at incredible speed, taking huge values ​​for the processor speed.

All you have to do is add a sleep line with 0.1.

time.sleep(0.1)

      

0


source







All Articles