让CPU占有率曲线听你指挥

解法一:简单的解法

int main()
{
	for (;;)
	{
		for (int i = 0; i < 9600000; i++)
			;
		Sleep(10);
	}

	return 0;
}

解法二:使用GetTickCount()和Sleep()

include <iostream>
include <windows.h>
using namespace std;
const DWORD busyTime = 10;       //10ms 
const DWORD idleTime = busyTime; //same ratio will lead to 50% cpu usage
DWORD startTime = 0;
int main()
{
	while (TRUE)
	{
		DWORD startTime = GetTickCount(); //busy loop
		while ((GetTickCount() - startTime) <= busyTime); //idle loop
		Sleep(idleTime);
	}
	
	return 0;
}

解法三:能动态适应的解法

//C# code
static void MakeUsage(float level)
{
	PerformanceCounter p = new PerformanceCounter("Processor", "Processor Time", "_Total");

	while (TRUE)
	{
		if (p.NextValue() > level)
		{
			System.Threading.Thread.Sleep(10);
		}
	}
}

解法四:正弦曲线

//C++ code to make task manager generate sine graph
#include "windows.h"
#include "stdlib.h"
#include "math.h"

//把一条正弦曲线0~2∏之间的弧度等分成200份进行抽样,计算每个抽样点的振幅
//然后每隔300ms的时间取下一个抽样点,并让CPU工作对应振幅的时间

const int SAMPLINE_COUNT = 200;   //抽样点数量
const double PI = 3.1415926535;   //pi值
const int TOTAL_AMPLITUDE = 300;  //每个抽样点对应的时间片

int main()
{
	DWORD busySpan[SAMPLINE_COUNT];
	int amplitude = TOTAL_AMPLITUDE / 2;
	double radian = 0.0;
	double radianIncrement = 2.0 / (double)SAMPLINE_COUNT; //抽样弧度的增量
	for (int i = 0; i < SAMPLINE_COUNT; i++)
	{
		busySpan[i] = (DWORD)(amplitude + (sin(PI * radian) * amplitude));
		radian += radianIncrement;
		//printf("%d\t%d\n", busySpan[i], TOTAL_AMPLITUDE - busySpan[i]);
	}

	DWORD startTime = 0;
	for (int j = 0; ; j = (j + 1) % SAMPLINE_COUNT)
	{
		startTime = GetTickCount();
		while ((GetTickCount() - startTime) <= busySpan[j])
			;
		Sleep(TOTAL_AMPLITUDE - busySpan[j]);
	}

	return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值