让用户决定CPU占用率

来源:互联网 发布:北京移动网络优化 出差 编辑:程序博客网 时间:2024/05/17 01:13

 

解决方法——绘制50%的直线:

代码:

#include
#include
#include
using namespace std;
int main()
{

     SetProcessAffinityMask(
         GetCurrentProcess(), // 获取当前进程的伪句柄
         0x00000001               //cpu mask 指定为第一个CPU
         );

     while(true)
    {
           //cout<<"program is running "<<endl;

            for(int i =0; i< n;i++)
           {
                 ;
             }

     }
      return 0;
}

 

解决方法二——绘制50%曲线:

使用GetTickCount()和Sleep()两个函数: GetTickCount()返回“系统启动到现在”所经历时间的毫秒值。最多能够统计到49.7天。

程序代码如下:

int main()
{
     int busyTime = 10; // 10 ms
     int idleTime = busyTime;

     DWORDstartTime = 0;
     SetProcessAffinityMask(
           GetCurrentProcess(),
         0x00000001        //cpu mask
         );

     while(true)
     {

       startTime = GetTickCount();
      // busy loop
      while((GetTickCount()- startTime) <= busyTime);

       // idle loop
       Sleep(idleTime);
     }

      return 0;
}