45fan.com - 路饭网

搜索: 您的位置主页 > 电脑频道 > 编程代码 > 阅读资讯:获取CPU频率的代码断的详细介绍

获取CPU频率的代码断的详细介绍

2016-08-29 20:51:41 来源:www.45fan.com 【

获取CPU频率的代码断的详细介绍

1通过注册表

CString ProcSpeedRead()
{
CString sMHz;
char Buffer[_MAX_PATH];
DWORD BufSize = _MAX_PATH;
DWORD dwMHz = _MAX_PATH;
HKEY hKey;

// open the key where the proc speed is hidden:
long lError = RegOpenKeyEx(HKEY_LOCAL_MACHINE,
"HARDWARE//DESCRIPTION//System//CentralProcessor//0",
0,
KEY_READ,
&hKey);

if(lError != ERROR_SUCCESS)
{// if the key is not found, tell the user why:
FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM,
NULL,
lError,
0,
Buffer,
_MAX_PATH,
0);
AfxMessageBox(Buffer);
return "N/A";
}

// query the key:
RegQueryValueEx(hKey, "~MHz", NULL, NULL, (LPBYTE) &dwMHz, &BufSize);

// convert the DWORD to a CString:
sMHz.Format("%i", dwMHz);

return sMHz;
}

2通过时钟循环与高精度计数器计算(非Inter处理器,例如AMD请更改RdTSC宏)

float CGettheProcessorSpeedDlg::ProcSpeedCalc()
{
/*
RdTSC:
It's the Pentium instruction "ReaD Time Stamp Counter". It measures the
number of clock cycles that have passed since the processor was reset, as a
64-bit number. That's what the
_emit lines do.*/
#define RdTSC __asm _emit 0x0f __asm _emit 0x31

// variables for the clock-cycles:
__int64 cyclesStart = 0, cyclesStop = 0;
// variables for the High-Res Preformance Counter:
unsigned __int64 nCtr = 0, nFreq = 0, nCtrStop = 0;


// retrieve performance-counter frequency per second:
if(!QueryPerformanceFrequency((LARGE_INTEGER *) &nFreq)) return 0;

// retrieve the current value of the performance counter:
QueryPerformanceCounter((LARGE_INTEGER *) &nCtrStop);

// add the frequency to the counter-value:
nCtrStop += nFreq;


_asm
{// retrieve the clock-cycles for the start value:
RdTSC
mov DWORD PTR cyclesStart, eax
mov DWORD PTR [cyclesStart + 4], edx
}

do{// retrieve the value of the performance counter until 1 sec has gone by:
QueryPerformanceCounter((LARGE_INTEGER *) &nCtr);
}while (nCtr < nCtrStop);

_asm
{// retrieve again the clock-cycles after 1 sec. has gone by:
RdTSC
mov DWORD PTR cyclesStop, eax
mov DWORD PTR [cyclesStop + 4], edx
}

// stop-start is speed in Hz divided by 1,000,000 is speed in MHz
return ((float)cyclesStop-(float)cyclesStart) / 1000000;
}

----摘自 CodeProject 作者Thomas Latuske

实例工程下载地址:

http://www.codeproject.com/useritems/Processor_Speed/Processor_Speed_demo.zip

 

本文地址:http://www.45fan.com/bcdm/69513.html
Tags: 获取 cpu 两个
编辑:路饭网
推广内容
推荐阅读
热门推荐
推荐文章
关于我们 | 联系我们 | 友情链接 | 网站地图 | Sitemap | App | 返回顶部