GEDDE5
GEDDE5

Reputation: 43

Relatively simple Python script using 100% cpu

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.

Basic structure

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

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.

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.

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

Upvotes: 4

Views: 33641

Answers (5)

The problem is that you don't have a sleep statement in the loop unless the if function is true, so you code is looping as ridiculous speed taking vast amounts of processor speed.

All you need to do is add an sleep line with 0.1.

time.sleep(0.1)

Upvotes: 4

Lennart Regebro
Lennart Regebro

Reputation: 172209

The question is why it should not use 100%. That's the default for anything you write. For it to not use 100% you need to have specific code that sits and waits for something to happen. If you do have that, then the error is in that code.

Upvotes: 2

carnieri
carnieri

Reputation: 1353

Perhaps there is a break or continue inside the while loop, so that your time.sleep(1) code is skipped. Are you sure the time.sleep(1) part is being executed?

Upvotes: 1

Mykola Kharechko
Mykola Kharechko

Reputation: 3211

100% CPU means that script runs well. I don't see any problem. If it prevents other programs to run well, run script under lower priority (nice)

Upvotes: 3

Gabriel Reid
Gabriel Reid

Reputation: 2536

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.

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.

Upvotes: 12

Related Questions