Write a program to control cpu usage 2

Source: Internet
Author: User

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

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.