学科前沿技术(让用户来决定Windows任务管理器的CPU占用率)

来源:互联网 发布:建筑设计院软件 编辑:程序博客网 时间:2024/04/30 03:03
题目:写一个程序,让用户来决定Windows任务管理器(Task Manager)的CPU占用率。程序越精简越好,计算机语言不限。例如,可以实现下面三种情况:

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

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

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

 

完整代码如下:

#include<windows.h>
#include
<cstdio>
#include
<cmath>

constint PERIOD= 60* 1000;//60,000 ms
constint COUNT = 200;

constdouble PI = 3.1415926535898;
constdouble GAP= (double)PERIOD/ COUNT;
constdouble FACTOR= 2* PI / PERIOD;

typedef
double Func(double);
inlineDWORD get_time()
{ returnGetTickCount(); }

doublecalc2(doublex) { return(1 +sin(FACTOR *x)) / 2;}

doublecalc3(double)
{
static doublecache[COUNT];
static intcount = 0;
static boolfirst = true;
if (first) {
doublex = 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;
returncache[count++];
}


doublecalc4(double){ return0.8;}

voidsolve(Func *calc)
{
doubletb = 0;
while(1){
unsigned ta
=get_time();
doubler =calc(tb);
if(r < 0|| r > 1)r = 1;
DWORD busy
=r *GAP;
while(get_time()- ta < busy) {}
Sleep(GAP
-busy);
tb
+=GAP;
}

}



voidrun()
{
Func
*func[]= {calc2, calc3, calc4 };
Func
*calc= func[1];
const intMAX_CPUS = 32;
HANDLE handle[MAX_CPUS];
DWORD thread_id[MAX_CPUS];
SYSTEM_INFO info;
GetSystemInfo(
&info);
const intnum =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);
}



intmain()
{
run();
}