VC++获得计算机CPU频率

// TestQueryPerformance.cpp : Defines the entry point for the console application.
//

//warning C4035: 'RDTSC' : no return value
#pragma warning(disable:4035)

#include <Windows.h>

//RDTSC-Read Time-Stamp Counter
//自开机以来CPU经历的时钟周期数
unsigned __int64 RDTSC()
{
	__asm _emit 0x0F;
	__asm _emit 0x31;
}

//CPU的频率
double CpuFrequency()
{
	//On a multiprocessor machine, it should not matter which processor is called.
	//However, you can get different results on different processors due to bugs in
	//the BIOS or the HAL. To specify processor affinity for a thread, use the SetThreadAffinityMask function.
	HANDLE hThread=GetCurrentThread();
	SetThreadAffinityMask(hThread,0x1);  

	//主板上高精度定时器的晶振频率
	//这个定时器应该就是一片8253或者8254
	//在intel ich7中集成了8254
	LARGE_INTEGER lFrequency;
	QueryPerformanceFrequency(&lFrequency);
	//printf("高精度定时器的晶振频率:%1.0fHz.\n",(double)lFrequency.QuadPart);

	//这个定时器每经过一个时钟周期,其计数器会+1
	LARGE_INTEGER lPerformanceCount_Start;
	QueryPerformanceCounter(&lPerformanceCount_Start);

	//RDTSC指令:获取CPU经历的时钟周期数
	__int64 _i64StartCpuCounter=RDTSC();

	//延时长一点,误差会小一点
	//int nTemp=100000;
	//while (--nTemp);
	Sleep(200); 

	LARGE_INTEGER lPerformanceCount_End;
	QueryPerformanceCounter(&lPerformanceCount_End);

	__int64 _i64EndCpuCounter=RDTSC();

	//f=1/T => f=计数次数/(计数次数*T)
	//这里的“计数次数*T”就是时间差
	double fTime=((double)lPerformanceCount_End.QuadPart-(double)lPerformanceCount_Start.QuadPart)
		/(double)lFrequency.QuadPart;

	return (_i64EndCpuCounter-_i64StartCpuCounter)/fTime;
}

int main(int argc, char* argv[])
{
	printf("CPU频率为:%1.6fMHz.\n",CpuFrequency()/1000000.0);
	return 0;
}


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值