简体   繁体   English

如何限制Windows上进程的CPU使用率?

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

I need to control my application's CPU usage to a certain limit. 我需要将应用程序的CPU使用率控制在一定的范围内。 My application will run on Win XP, Vista, Win7 and Windows 8. 我的应用程序将在Win XP,Vista,Win7和Windows 8上运行。

I tried implementing to get the current process's CPU usage and using the Sleep() method.(I used the APIs GetProcessTimes& GetSystemTimes) 我尝试实现以获取当前进程的CPU使用率并使用Sleep()方法。(我使用了API 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. 我可以编写一个应用程序来监视进程的CPU使用情况,并且每当CPU达到允许的限制时,就停止该进程并继续进行。

Thanks in advance for your help. 在此先感谢您的帮助。

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. 您可以通过将感兴趣的进程添加到Job对象并在Job对象上设置限制来限制进程或任何其他进程的CPU使用率。

One of the resource limits which can be configured for Job objects is CPU usage: 可以为Job对象配置的资源限制之一是CPU使用率:

If you have to use the pre-Windows 8 approach, pay careful attention to the note: 如果必须使用Windows 8之前的方法,请注意以下注意事项:

To register for notification when this limit is exceeded without terminating processes, use the SetInformationJobObject function with the JobObjectNotificationLimitInformation information class 若要在超过此限制时进行注册以通知而不终止进程,请将SetInformationJobObject函数与JobObjectNotificationLimitInformation信息类一起使用

如果您只是想给该进程一个较低的优先级以便更好地使用其他线程,则可以使用SetThreadPriority设置其优先级,例如:

SetThreadPriority(GetCurrentThread(), THREAD_PRIORITY_BELOW_NORMAL);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM