基本思路是新建一线程,让这个线程只在某一cpu上运行。这个线程的作用是控制单个cpu的占用率。
#include <Windows.h>
#include <stdlib.h>
#include <math.h>
const double SPLIT = 0.01;
const int COUNT = 200;
const double PI = 3.1415926;
const int INTERVAL = 300;
static DWORD WINAPI myProc(LPVOID p)
{
DWORD busySpan[COUNT];
DWORD idleSpan[COUNT];
int half = INTERVAL / 2;
double radian = 0.0;
for (int i=0; i<COUNT; i++)
{
busySpan[i] = (DWORD)(half + half * sin(PI * radian));
idleSpan[i] = INTERVAL - busySpan[i];
radian += SPLIT;
}
DWORD startTime = 0;
int j=0;
while (true)
{
j=j%COUNT;
startTime = GetTickCount();
while ( (GetTickCount() - startTime) <= busySpan[j])
{
;
}
Sleep(idleSpan[j]);
j++;
}
}
int _tmain(int argc, _TCHAR* argv[])
{
char szbuf[200];
DWORD id;
HANDLE h = CreateThread(NULL, 0, myProc, &szbuf, CREATE_SUSPENDED, &id);
if (NULL == h)
{
printf("error /n");
return 0;
}
SetThreadAffinityMask(h, 1);
ResumeThread(h);
if (WaitForSingleObject(h, INFINITE) != WAIT_OBJECT_0)
{
CloseHandle(h);
printf("error /n");
return 0 ;
}
CloseHandle(h);
return 0;
}