码迷,mamicode.com
首页 > 其他好文 > 详细

《编程之美》之如何控制CPU的暂用率固定在50%

时间:2014-07-10 10:36:20      阅读:213      评论:0      收藏:0      [点我收藏+]

标签:style   blog   cti   for   io   line   

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

  

《编程之美》之如何控制CPU的暂用率固定在50%,布布扣,bubuko.com

《编程之美》之如何控制CPU的暂用率固定在50%

标签:style   blog   cti   for   io   line   

原文地址:http://www.cnblogs.com/binmaizhai/p/3812306.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!