《编程之美》之如何控制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;
}

  

转载于:https://www.cnblogs.com/binmaizhai/p/3812306.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值