今天开始看编程之美 。第一个问题是CPU的使用率控制,微软的问题果然高大上,我一看就傻了,啥也不知道。没追求直接看答案试了一下。发现自己电脑太好了,4核8线程,程序乱飘。加了一个进程绑定,可以控制一个CPU的占有率。
代码结果如下:
#include"stdio.h" #include <Windows.h> void main() { //前三行可以不要 SYSTEM_INFO SystemInfo; GetSystemInfo(&SystemInfo); int CpuNum=SystemInfo.dwNumberOfProcessors; //获取cpu数目 SetThreadAffinityMask(GetCurrentThread(), 1); //线程与cpu绑定 while(1) { for(int i=0;i<3400000000;i++); Sleep(10); } }
现在的疑问是,不知道如何指定具体的某一个CPU. SetThreadAffinityMask的第二个参数改了后和自己想要的不一样。也不知道如何实现所有CPU占有率的同时控制。
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
第二个版本 按照书中给的可以根据不同的CPU精确计算时间的代码 效果好很多
//比初始最简单的版本好很多 CPU使用中可以得到非常漂亮的直线 不像之前有锯齿 #include<stdio.h> #include<Windows.h> void main() { const int busyTime=10; //10ms const int idleTime=busyTime; //50% cpu useage int startTime=0; SetThreadAffinityMask(GetCurrentThread(), 1); //cpu绑定 while(1) { int startTime=GetTickCount(); //busy loop while(GetTickCount()-startTime<=busyTime); //idle loop Sleep(idleTime); } }
原文:http://www.cnblogs.com/dplearning/p/3567714.html