首页 > 代码库 > 《编程之美》之如何控制CPU的暂用率固定在50%
《编程之美》之如何控制CPU的暂用率固定在50%
《编程之美》第一章 让CPU暂用率听你指挥的粗糙实现,如何控制CPU的暂用率固定在50%
#include <stdio.h>#include <Windows.h>#ifdef __cplusplus extern "C" { #endif #include <Powrprof.h> #ifdef __cplusplus } #endif #define GetCPUTickCount() __rdtsc()typedef struct _PROCESSOR_POWER_INFORMATION { ULONG Number; ULONG MaxMhz; ULONG CurrentMhz; ULONG MhzLimit; ULONG MaxIdleState; ULONG CurrentIdleState;} PROCESSOR_POWER_INFORMATION, *PPROCESSOR_POWER_INFORMATION;int main(int argc, char* argv[]){ SYSTEM_INFO SystemInfo; GetSystemInfo(&SystemInfo); printf("dwNumberOfProcessors=%u, dwActiveProcessorMask=%u, wProcessorLevel=%u,wProcessorArchitecture=%u, dwPageSize=%u ", SystemInfo.dwNumberOfProcessors, SystemInfo.dwActiveProcessorMask, SystemInfo.wProcessorLevel, SystemInfo.wProcessorArchitecture,SystemInfo.dwPageSize); if(SystemInfo.dwNumberOfProcessors <= 1) return 0; DWORD dwtmp = 0x0001; //进程与指定cpu绑定,dwtmp第几位为1表示第几个CPU dwtmp = 0x0002; SetProcessAffinityMask(GetCurrentProcess(), dwtmp); //线程与指定cpu绑定 //SetThreadAffinityMask(GetCurrentThread(),dwMask); //unsigned __int64 uiCpuTick = GetCPUTickCount(); unsigned __int64 uiTick = GetTickCount(); //获取CPU的时钟周期 info.CurrentMhz单位是MHZ = 1000000HZ //表示CPU 1s中可以做多少次for循环 PROCESSOR_POWER_INFORMATION info; long lRet = CallNtPowerInformation(ProcessorInformation, NULL, 0, &info, SystemInfo.dwNumberOfProcessors * sizeof(info)); unsigned int uiMhz = info.CurrentMhz * 1000000; for ( ; ; ) { for (int i = 0; i < uiMhz/500; i++) ; Sleep(30); } return 0;}
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。