The previous section describes how to control the CPU usage through simple cyclic operations. Link: www.2cto.com/kf/201110/425456.html
However, by calling the GetTickCount () function of the system, you can obtain the current time value from the system startup. This time value can also be used to control the busy time slice and idle time slice of the system. Let the system keep repeating a time slice, and sleep a time slice. In this way, after a second, the CPU usage will also be close to 50%.
Code:
// Cpu_2.cpp: Defines the entry point for the console application.
//
# Include "stdafx. h"
# Include "windows. h"
Int _ tmain (int argc, _ TCHAR * argv [])
{
Const DWORD busyTime = 10;
Const DWORD idleTime = busyTime;
DWORD startTime = GetTickCount ();
While (true)
{
StartTime = GetTickCount ();
While (GetTickCount ()-startTime <= busyTime)
{
// IDLE
}
Sleep (idleTime );
}
Return 0;
}
Set the size of the idle time slice and the busy time slice, and then perform two operations alternately. Use the GetTickCount () function to get the current start time, and then continuously obtain the system start time to calculate the difference between the time slice and the time slice. When the difference reaches the time slice, the system proceeds to another time slice operation.
Execution result
I don't know why, because the CPU is dual-core, it turns into a core task, and a core is sleep. Special Program processing may also be required for the dual-core CPU. There should be no problem with single-core CPU.
I hope you will give me a lot of advice on how to handle this dual-core problem.
Author: Watkins. Song