解法一:简单的解法
int main()
{
for (;;)
{
for (int i = 0; i < 9600000; i++)
;
Sleep(10);
}
return 0;
}
解法二:使用GetTickCount()和Sleep()
include <iostream>
include <windows.h>
using namespace std;
const DWORD busyTime = 10; //10ms
const DWORD idleTime = busyTime; //same ratio will lead to 50% cpu usage
DWORD startTime = 0;
int main()
{
while (TRUE)
{
DWORD startTime = GetTickCount(); //busy loop
while ((GetTickCount() - startTime) <= busyTime); //idle loop
Sleep(idleTime);
}
return 0;
}
解法三:能动态适应的解法
//C# code
static void MakeUsage(float level)
{
PerformanceCounter p = new PerformanceCounter("Processor", "Processor Time", "_Total");
while (TRUE)
{
if (p.NextValue() > level)
{
System.Threading.Thread.Sleep(10);
}
}
}
解法四:正弦曲线
//C++ code to make task manager generate sine graph
#include "windows.h"
#include "stdlib.h"
#include "math.h"
//把一条正弦曲线0~2∏之间的弧度等分成200份进行抽样,计算每个抽样点的振幅
//然后每隔300ms的时间取下一个抽样点,并让CPU工作对应振幅的时间
const int SAMPLINE_COUNT = 200; //抽样点数量
const double PI = 3.1415926535; //pi值
const int TOTAL_AMPLITUDE = 300; //每个抽样点对应的时间片
int main()
{
DWORD busySpan[SAMPLINE_COUNT];
int amplitude = TOTAL_AMPLITUDE / 2;
double radian = 0.0;
double radianIncrement = 2.0 / (double)SAMPLINE_COUNT; //抽样弧度的增量
for (int i = 0; i < SAMPLINE_COUNT; i++)
{
busySpan[i] = (DWORD)(amplitude + (sin(PI * radian) * amplitude));
radian += radianIncrement;
//printf("%d\t%d\n", busySpan[i], TOTAL_AMPLITUDE - busySpan[i]);
}
DWORD startTime = 0;
for (int j = 0; ; j = (j + 1) % SAMPLINE_COUNT)
{
startTime = GetTickCount();
while ((GetTickCount() - startTime) <= busySpan[j])
;
Sleep(TOTAL_AMPLITUDE - busySpan[j]);
}
return 0;
}