Set CPU priority on Windows in C++
Jump to navigation
Jump to search
In Windows, CPU priority, as the name suggests, will make the process have higher CPU priority than other processes. There are 7 types of CPU priorities. From lowest to highest, they are: "Idle", "Low", "Below Normal", "Normal", "Above Normal", "High", and "Realtime". The function requires at least Windows NT 4.0. This works in both Visual C++ and MinGW.
Example code
#include <iostream>
#include <windows.h>
int main() {
SetPriorityClass(GetCurrentProcess(), REALTIME_PRIORITY_CLASS); // Get the current process and set it to "Realtime" priority class.
std::cin.get(); // Make the process stay open
return 0;
}
The above example code will get the current process, set it to the "Realtime" priority, and keep it running so we can verify. There are also other priority classes we can use.
Class | Description |
---|---|
IDLE_PRIORITY_CLASS | Programs under this class will only when the system is idle. |
BELOW_NORMAL_CLASS | Programs under this class will be above IDLE_PRIORITY_CLASS and below NORMAL_PRIORITY_CLASS. |
NORMAL_PRIORITY_CLASS | The default priority class, it has no special scheduling needs. This is above BELOW_NORMAL_PRIORITY_CLASS and below ABOVE_NORMAL_CLASS. |
ABOVE_NORMAL_PRIORITY_CLASS | Programs under this class will be above NORMAL_PRIORITY_CLASS, but below HIGH_PRIORITY_CLASS. |
HIGH_PRIORITY_CLASS | This should be used if your process is performing time-critical tasks. High priority can use nearly all of the CPU, so be advised and take caution while using this. This class is above ABOVE_NORMAL_PRIORITY_CLASS, but below REALTIME_PRIORITY_CLASS. |
REALTIME_PRIORITY_CLASS | This is the highest priority class possible. Processes set to this will take priority above any task, even critical operating system tasks. Be careful - misusage of this can lock up a system. |