0

I wrote an infinite loop in python to print No! in the output.

while True:
    print("No!")

When I execute it, I see its process (pythonw.exe) in Windows-Task-Manager that uses 60% of the CPU. I did a right-click on its process and change the priority to Low. it use 60% of CPU again! Then I change the priority to Real-Time. It still uses 60% of CPU !

Update: My total CPU usage for all process is 80%!!! and 20% is free! Why this python loop doesn't use this 20%?!

What's wrong with priority? Why it doesn't change?

TheGoodUser
  • 1,195

2 Answers2

2

The priority determines which thread gets to run when multiple threads are competing for CPU time. If nothing else wants the CPU, your program's thread(s) will get up to 100% CPU time, as and when needed, regardless of priority.

In your case the Python process is the only one needing a lot of CPU time, so it will get all it asks for. If your system were otherwise busy, then you would see your 60% drop much more than if it had normal priority.

You should test it against another CPU-consuming program running at the same time, eg in a CMD shell run test.cmd containing:

:Loop
dir /s c:\
goto Loop

Then you will see the effects of changing the priority of your competing process. Note that the CPU requirements of this example will vary, depending on the CPU speed, the number of files in c:\ and disc cache sizes; redirecting the dir output to >nul: will increase the CPU load.

AFH
  • 17,958
0

There's nothing wrong with priority.

It is a common assumption that a low or medium priority set on a process will cause the operating system to limit the CPU time available to the process's threads - so, setting its priority higher should let it use more CPU!

But that is not what happens.

You can have a process set to the lowest possible priority, and if its code never needs to wait for anything, and if nothing else on the system wants CPU time, that process will get 100% of the CPU.

If a process gets less than 100% CPU, and nothing of equal or higher priority is trying to run, then that simply means that the process's threads are spending part of their time not wanting the CPU.

What is a thread doing if it doesn't want the CPU? Most of the time it's "waiting". Threads wait when they need something to happen that doesn't involve running the thread's own code in the CPU. Usually they're waiting for an I/O operation to complete. This could be an I/O request explicitly requested by the thread, or it could be, for example, a hard page fault. (On the other hand, time spent "waiting" for RAM read or write latency is all part of the thread's CPU time. That's not considered I/O.)

Your loop in Python includes a "print" funciton. That's an I/O operation, even if it's only to the screen.

You could use Windows Performance Analyzer to get details about just what pythonw.exe is doing that's making it wait.

You may wish to review my answer here.