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;
int idleTime=busyTime;
int64 startTime=0;
while(true)
{
}
}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();
}