1th Chapter Game Music let the CPU occupancy curve listen to your command. Controlling CPU Utilization

Source: Internet
Author: User
Tags cpu usage

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

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.