在任务管理器的一个刷新周期内,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
#include
using namespace std;int main()
{const DWORD busyTime &#61; 100;const DWORD idleTime &#61; busyTime;LONG64 startTime &#61; 0;while(true){//GetTickCount返回从操作系统启动到现在所经过的毫秒数&#xff0c;返回值是DWORD。DWORD startTime &#61; GetTickCount();//busy loopwhile((GetTickCount() - startTime) <&#61; busyTime);//idle loopSleep(idleTime);}return 0;
}
2> .正弦曲线&#xff1a;
#include
#include
using namespace std;//把一条正弦曲线0~2π之间的弧度等分为200份进行抽样&#xff0c;计算每个抽样点的振幅、
//然后每隔300ms的时间取下一个抽样点&#xff0c;并让cpu工作对应振幅的时间
const int SAMPLING_COUNT &#61; 200;//抽样点数量
const double PI &#61; 3.1415926535;//π值
const int TOTAL_AMPLITUDE &#61; 300;//每个抽样点对应的时间片int main()
{DWORD busySpan[SAMPLING_COUNT];//忙碌时间跨度int amplitude &#61; TOTAL_AMPLITUDE / 2;//设置振幅为150double radian &#61; 0.0;//初始化弧度为0.0double radianIncrement&#61; 2.0 / (double)SAMPLING_COUNT;//设置弧度增量for (int i &#61; 0;i }
双核情况&#xff1a;
参考&#xff1a;http://www.cnblogs.com/growup/archive/2012/03/13/2394783.html,http://cooker.iteye.com/blog/652604
#include
#include
#include
using namespace std;void running(int seconds) { Sleep(seconds*1000);cout<<"sleep for "<}int main()
{SetThreadAffinityMask(GetCurrentThread(), 1);LARGE_INTEGER start, end; LARGE_INTEGER freq;//timeConsuming();QueryPerformanceFrequency(&freq);cout <<"freq.QuadPart:" <}