JChan
JChan

Reputation: 1451

How to limit the Process's CPU usage on Windows?

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

Answers (2)

Ben Voigt
Ben Voigt

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:

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

chappy
chappy

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

Related Questions