In the previous section, we talked about CPU usage control through PerformanceCounter.
Last connection: http://www.bkjia.com/kf/201110/107758.html
This section describes how to implement a sine curve for controlling CPU usage.
Within a period of time, adjust the CPU usage display by controlling the CPU busy time.
Code:
// Cpu_4.cpp: Defines the entry point for the console application.
//
# Include "stdafx. h"
# Include "stdlib. h"
# Include "stdio. h"
# Include "iostream"
# Include "math. h"
# Include "windows. h"
Using namespace std;
Const int SAMPLING_COUNT = 200;
Const double PI = 3.1415926;
Const int TOTAL_AMPLITUDE = 250;
Int _ tmain (int argc, _ TCHAR * argv [])
{
Cout <"test the cpu" <endl;
DWORD cpuRate [SAMPLING_COUNT];
Int ampl_= TOTAL_AMPLITUDE/2;
Double radian = 0.0;
Double radianIncrement = 2.0/(double) SAMPLING_COUNT;
For (int I = 0; I <SAMPLING_COUNT; I ++)
{
CpuRate [I] = (DWORD) (amplate + (sin (PI * radian) * amplate ));
Radian + = radianIncrement;
}
DWORD startTime = GetTickCount ();
For (int j = 0; j = (j + 1) % SAMPLING_COUNT)
{
StartTime = GetTickCount ();
While (GetTickCount ()-startTime) <= cpuRate [j])
{
}
Sleep (TOTAL_AMPLITUDE-cpuRate [j]);
}
Return 0;
}
Explanation:
Const int SAMPLING_COUNT = 200; defines the number of sampling points in a sine cycle
Const int total_ampl = 150; defines the size of a scheduled time slice, so that the CPU busy and idle time can be controlled through this time slice.
DWORD cpuRate [SAMPLING_COUNT]; records the CPU usage of each sampling point. In fact, the actual storage is the CPU busy time.
Int ampl_= total_ampl/2; record the size of the half-time slice, because the control of the sine function starts from the center, that is, sin0.
Double radianIncrement = 2.0/(double) SAMPLING_COUNT; record the increment of each sampling point
For (int I = 0; I <SAMPLING_COUNT; I ++)
{
CpuRate [I] = (DWORD) (amplate + (sin (PI * radian) * amplate ));
Radian + = radianIncrement;
}
// The above code cyclically calculates the CPU usage of each sampling point. The actual storage is the size of the CPU busy time in this time slice. Control the CPU usage by controlling the ratio of busy time.
DWORD startTime = GetTickCount ();
For (int j = 0; j = (j + 1) % SAMPLING_COUNT)
{
StartTime = GetTickCount ();
While (GetTickCount ()-startTime) <= cpuRate [j])
{
}
Sleep (TOTAL_AMPLITUDE-cpuRate [j]);
}
// Control the interoperation between the CPU in the busy and idle time slices to control the CPU usage.
If the test result is of different time slice sizes, the results are different. After testing, when the time slice size is 150, the best effect is achieved.
The time slice size is 150:
The time slice size is 100:
Further debugging is required to make the CPU curve more perfect.
From: Watkins. Song