写程序让用户来决定Windows任务管理器的CPU占有率

本文提供三种模拟CPU占用率的方法:固定50%占用率、由命令行参数设定具体占用率及正弦曲线变化的占用率。通过Windows API函数GetTickCount()和Sleep()实现精确的时间控制。

1、CPU的占用率固定在50%,为一条直线

代码:

   #include <windows.h>    
   int main(void)    
    {        
//50%  
int busyTime=10;   
     int idleTime=busyTime;   
     _int64 startTime;             
SetThreadAffinityMask(GetCurrentProcess(), 0x00000001);       
while(true)       
{            startTime=GetTickCount();  //获取从系统从开机到此刻 
        while((GetTickCount()-startTime)<=busyTime)    
        {                ;            }        
          Sleep(idleTime);    
}      
return 0;  
 }  


2、CPU的占用率为一条直线,但是具体占用率由命令行参数决定(参数范围1~100)

#include<stdio.h>

void main()

{

int busyTime=10;         //10ms

int idleTime=busyTime;

 

int64 startTime=0;

while(true)

{

      startTime=GetTickCount();

 

      while( GetTickCount()-starTime <=busyTime ) ;

 

      sleep(idleTime);

}

}

3、CPU的占用率状态是一个正弦曲线

代码:

#include<windows.h>
#include<cstdio>
#include<cmath>
const int PERIOD = 60 * 1000; //60,000 ms
const int COUNT = 200;
const double PI = 3.1415926535898;
const double GAP = (double)PERIOD / COUNT;
const double FACTOR = 2 * PI / PERIOD; 
typedef double Func(double); 
inline DWORD get_time() { return GetTickCount(); }
double calc2(double x) { return (1 + sin(FACTOR * x)) / 2;}

double calc3(double)
{
 static double cache[COUNT];
 static int count = 0;
 static bool first = true;
 if (first) {
 double x = 0.0;
 for (int i = 0; i < COUNT; ++i, x += GAP) 
 cache[i] = (1.0 + sin(FACTOR * x)) / 2.0; 
 first = false;
 }
 if (count >= COUNT) count = 0;
 return cache[count++]; 
}
double calc4(double) { return 0.8;}
void solve(Func *calc)
{
 double tb = 0;
 while(1) {
 unsigned ta = get_time();
 double r = calc(tb);
 if (r < 0 || r > 1) r = 1;
 DWORD busy = r * GAP;
 while(get_time() - ta < busy) {}
 Sleep(GAP - busy);
 tb += GAP;
 }
}
void run()
{
 Func *func[] = { calc2, calc3, calc4 };
 Func *calc = func[1];
 const int MAX_CPUS = 32;
 HANDLE handle[MAX_CPUS];
 DWORD thread_id[MAX_CPUS];
 SYSTEM_INFO info;
 GetSystemInfo(&info);
 const int num = info.dwNumberOfProcessors;
 for (int i = 0; i < num; ++i) {
 if ( (handle[i] = CreateThread(NULL, 0, (LPTHREAD_START_ROUTINE)solve,
 (VOID*)calc, 0, &thread_id[i])) != NULL) 
 SetThreadAffinityMask(handle[i], i + 1);
 }
 WaitForSingleObject(handle[0],INFINITE); 
}
int main()
{
 run();
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值