1.1 Let the CPU usage curve listen to your command:
Solution One: Code Listing 1-1
int main ()
{
for (;;
{
The number of seconds a CPU executes
for (int i = 0; I <9600000; i++)
;
Sleep (10);
}
return 0;
}
Solution Two: Code Listing 1-2:
int busyTime = 10; Ten MS
int IdleTime =busytime; Same ratio'll lead to50% CPU usage
Int64 starttime = 0;
while (true)
{
StartTime = GetTickCount ();
Busy loop
while ((GetTickCount ()-starttime) <= busyTime)
;
Idle loop
Sleep (IdleTime);
Solution Three: The solution that can adapt dynamically
C # code
static void Makeusage (float level)
{
PerformanceCounter p = new PerformanceCounter ("Processor", "%processor Time", "_total");
if (p==null)
{
Return
}
while (true)
{
if (P.nextvalue () > Level)
System.Threading.Thread.Sleep (10);
}
Solution Four: Let the CPU appear as a sine curve
C + + code to Maketask Manager generate sine graph
#include "Windows.h"
#include "Stdlib.h"
#include "math.h"
const double split= 0.01;
const int COUNT = 200;
Const double PI = 3.14159265;
const int interval= 300;
int _tmain (INTARGC, _tchar* argv[])
{
DWORD Busyspan[count]; Array of busy times
DWORD Idlespan[count]; Array of idle times
int half = INTERVAL/2;
Double radian = 0.0;
for (int i = 0; i < COUNT; i++)
{
Busyspan[i] = (DWORD) (Half + (sin (PI * radian) * half));
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 + +;
}
return 0;
Summary: Invoke the Windows API implementation program to control CPU usage