控制CPU占有率
CPU利用率//CPU利用率是指 CPU执行非系统空闲进程的时间 / CPU总的执行时间 相关的API函数:- GetTickCount(); //返回(retrieve)从操作系统启动所经过(elapsed)的毫秒数,它的返回值是DWORD。
- Sleep();//让当前线程挂机一段时间
- WaitForSingleObject()// 详见http://baike.so.com/doc/6708461.html
复制代码
让CPU占有率为一条直线- DWORD WINAPI LineThread(LPVOID Line)
- {
- DWORD busyTime = 150;
- DWORD idleTime = busyTime;
- DWORD startTime ;
- while(true)
- {
- startTime = GetTickCount();
- while((GetTickCount()-startTime) <= busyTime)
- ;
- Sleep(idleTime);
- }
- return 0;
- }
复制代码
让CPU占有率为一条正弦曲线
- #define COUNT 200
- const double PI = 3.14159265;
- const int Total = 300;
-
- DWORD WINAPI SinThread(LPVOID Sin)
- {
- DWORD busy[COUNT];
- DWORD idle[COUNT];
- int half = 150;
- double radian = 0.0;
- double radianIncrement = 0.01;
- DWORD startTime;
- int i;
- for (i = 0; i < COUNT; i++)
- {
- busy = (DWORD)(half + half*sin(PI*radian));
- idle = (DWORD)(Total - busy);
- radian += radianIncrement;
- }
- i = 0;
- while(true)
- {
- i %= COUNT;
- startTime = GetTickCount();
- while((GetTickCount()-startTime) <= busy)
- ;
- Sleep(idle);
- i++;
- }
- return 0;
- }
复制代码 执行效果:
我的电脑有4个核心,我让第一个核心执行正弦曲线,第二个核心执行直线;
执行代码如下:
- int main()
- {
- HANDLE hThread1, hThread2;
- DWORD dwThreadId1, dwThreadId2;
- hThread1 = CreateThread(NULL, 0, SinThread, 0, CREATE_SUSPENDED, &dwThreadId1);
- hThread2 = CreateThread(NULL, 0, LineThread, 0, CREATE_SUSPENDED, &dwThreadId2);
- SetThreadAffinityMask(hThread1, 1);
- SetThreadAffinityMask(hThread2, 2);
- ResumeThread(hThread1);
- ResumeThread(hThread2);
- SuspendThread(GetCurrentThread());
- return 0;
- }
复制代码
|