分享

《编程之美》上控制CPU使用率曲线的题目

 bad_boy 2012-04-15
编程之美上控制CPU使用率曲线的题目 我的解答(原)
注释掉的部分是单线程版本,如果是双核的CPU,那么CPU使用率峰值在50%左右,因为有其他程序运行,所以可能会有点影响

考虑到双核或者多核,于是使用多线程,主线程直接Sleep

先上截图





下面是代码

作者:Gods_巨蚁(博主)

#include <windows.h>
#include <cmath>
#include <process.h> //for 多线程

using namespace std;

/*
void DoSth(unsigned iDelay)
{
unsigned iStart = ::GetTickCount();
while(::GetTickCount() - iStart < iDelay);
}

int main() //单核情况
{
double x = 0.0;
double y;
while(1)
{
y = sin(x);

unsigned iDelay = static_cast<int>(500 * y) + 500;
DoSth(iDelay);
Sleep(1000 - iDelay);

x += 0.314;
if(x >= 6.28)
x = 0;
}
}
*/


unsigned __stdcall mtThreadDoSth(void * param)
{
unsigned iDelay = reinterpret_cast<int>(param);
int iStart = ::GetTickCount();
while(::GetTickCount() - iStart < iDelay);

return 0;
}

//多核情况
int main(int argc, char **argv)
{
unsigned long thd;
unsigned tid;

int cCpus = 2; //设置CPU数量
double x = 0.0;
double y;
while(1)
{
y = sin(x);
unsigned iDelay = static_cast<int>(500 * y) + 500;
for(int i = 0; i < cCpus; ++i)
{
thd = _beginthreadex(NULL,
0,
mtThreadDoSth,
(void *)iDelay,
0,
&tid);
if(thd != NULL){
CloseHandle((HANDLE)thd);
}
}
x += 0.314;
if(x >= 6.28)
x = 0;
Sleep(1000);
}

}

    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约

    类似文章 更多