CPU占用率(单核,双核)

在任务管理器的一个刷新周期内,CPU忙碌(执行应用程序)的时间和刷新周期总时间的比率,就是CPU的忙碌率。即,任务管理器中显示的是每个刷新周期内CPU占用率的平均值。通过调节CPU忙/闲的比例,就可以实现控制任务管理器中显示的CPU占用率。

GetTickcount函数:它返回从操作系统启动到当前所经过的毫秒数,常常用来判断某个方法执行的时间,其函数原型是DWORD GetTickCount(void),返回值以32位的双字类型DWORD存储,因此可以存储的最大值是2^32 ms约为49.71天,因此若系统运行时间超过49.71天时,这个数就会归0,MSDN中也明确的提到了:"Retrieves the number of milliseconds that have elapsed since the system was started, up to 49.7 days."。因此,如果是编写服务器端程序,此处一定要万分注意,避免引起意外的状况。

单核情况:

1>. 50%忙碌率:

#include <iostream>
#include <Windows.h>
using namespace std;

int main()
{
	const DWORD busyTime = 100;
	const DWORD idleTime = busyTime;
	LONG64 startTime = 0;
	while(true)
	{
		//GetTickCount返回从操作系统启动到现在所经过的毫秒数,返回值是DWORD。
		DWORD startTime = GetTickCount();
		//busy loop
		while((GetTickCount() - startTime) <= busyTime)
			;
		//idle loop
		Sleep(idleTime);
	}
	return 0;
}


2> .正弦曲线:

#include <iostream>
#include <Windows.h>
using namespace std;

//把一条正弦曲线0~2π之间的弧度等分为200份进行抽样,计算每个抽样点的振幅、
//然后每隔300ms的时间取下一个抽样点,并让cpu工作对应振幅的时间
const int SAMPLING_COUNT = 200;//抽样点数量
const double PI = 3.1415926535;//π值
const int TOTAL_AMPLITUDE = 300;//每个抽样点对应的时间片

int main()
{
	DWORD busySpan[SAMPLING_COUNT];//忙碌时间跨度
	int amplitude = TOTAL_AMPLITUDE / 2;//设置振幅为150
	double radian = 0.0;//初始化弧度为0.0
	double radianIncrement= 2.0 / (double)SAMPLING_COUNT;//设置弧度增量
	for (int i = 0;i < SAMPLING_COUNT;++i)
	{
		busySpan[i] = (DWORD)(amplitude + sin(PI * radianIncrement * i) * amplitude);
	}

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

	return 0;
}

双核情况:

参考:http://www.cnblogs.com/growup/archive/2012/03/13/2394783.html,http://cooker.iteye.com/blog/652604

#include <windows.h>  
#include <string>
#include <iostream>
using namespace std;

void running(int seconds)  {	
	Sleep(seconds*1000);
	cout<<"sleep for "<<seconds<<"(s)"<<endl;
}

int main()
{
	SetThreadAffinityMask(GetCurrentThread(), 1);
	LARGE_INTEGER start, end;       
	LARGE_INTEGER freq;
	//timeConsuming();
	QueryPerformanceFrequency(&freq);
	cout << "freq.QuadPart:" << freq.QuadPart << endl;

	QueryPerformanceCounter(&start);//start
	cout<<"start.QuadPart = "<<start.QuadPart<<endl;//output start
	running(3); //running 3 seconds
	QueryPerformanceCounter(&end); //end
	cout<<"end.QuadPart = "<<end.QuadPart<<endl;	//output end 

	cout<<"consume value = end.QuadPart - start.QuadPart = "<<(end.QuadPart - start.QuadPart)<<endl;
	//利用两次获得的计数之差和时钟频率,计算出事件经历的精确时间
	cout<<"(consume value/(double)freq.QuadPart) Time consumed = "<<
		(end.QuadPart - start.QuadPart)/(double)freq.QuadPart<<"(s)"<<endl;  //output consumed time
	return 0;
}


你可能感兴趣的:(CPU占用率(单核,双核))