Reputation: 1451
I need to control my application's CPU usage to a certain limit. My application will run on Win XP, Vista, Win7 and Windows 8.
I tried implementing to get the current process's CPU usage and using the Sleep() method.(I used the APIs GetProcessTimes& GetSystemTimes)
pseudo code:
for(;;)
{
//Get the current process's CPU Usage
int cpuUsage = CalculateCPUUsage();
if(cpuUsage > 50)
Sleep(10)
else
{
//Project implementation code
}
}
Question:
Can I write an application to monitor a process's CPU Usage and whenever the CPU reaches the allowed limit, stop the process and continue it.
Thanks in advance for your help.
Upvotes: 4
Views: 6713
Reputation: 283634
You can limit the CPU usage of your process or any other process by adding the process of interest to a Job object, and placing limits on the Job object.
One of the resource limits which can be configured for Job objects is CPU usage:
JOBOBJECT_BASIC_LIMIT_INFORMATION
available since Windows XP and 2003JOBOBJECT_CPU_RATE_CONTROL_INFORMATION
new in Windows 8 and Server 2012.If you have to use the pre-Windows 8 approach, pay careful attention to the note:
To register for notification when this limit is exceeded without terminating processes, use the SetInformationJobObject function with the JobObjectNotificationLimitInformation information class
Upvotes: 1
Reputation: 1107
If you're just trying to give the process a lower priority in order to be nicer to other threads, you can set its priority with SetThreadPriority, e.g.:
SetThreadPriority(GetCurrentThread(), THREAD_PRIORITY_BELOW_NORMAL);
Upvotes: 1