《编程之美》第一章 让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;
}