C++获取CPU频率

#include <windows.h>
#include <stdio.h>
#include <intrin.h>

#pragma intrinsic(__rdtsc)

int main()
{ 
	unsigned __int64 t1,t2;
	t1 = __rdtsc();	//返回处理器时间戳(自上次CPU重置以来的时钟周期数-64位无符号整数)
	Sleep(1000);
	t2 = __rdtsc();
	printf_s("CPU Freq:%lldMHz\n",(t2 - t1) / 1000000);//CPU Freq:2209MHz
	return 0;
}

此方法无法排除程序运行过程中操作系统和后台运行程序所占用的时钟周期

#include <windows.h>
#include <stdio.h>
#include <time.h>
#include <iostream>
using namespace std;

int main()
{ 
	LARGE_INTEGER m_liPerfFreq = {  0 };
	//获取每秒多少CPU Performance Tick 
	QueryPerformanceFrequency(&m_liPerfFreq);

	LARGE_INTEGER m_liPerfStart = {  0 };
	LARGE_INTEGER liPerfNow = {  0 };
	for (int i = 0; i < 100; i++) { 
		QueryPerformanceCounter(&m_liPerfStart);
		Sleep(99);
		// 计算CPU运行到现在的时间
		QueryPerformanceCounter(&liPerfNow);
		int time = (((liPerfNow.QuadPart - m_liPerfStart.QuadPart) * 1000) / m_liPerfFreq.QuadPart);
		cout <<"1:"<< time << "ms" << endl;//99ms
		clock_t start, finish;
		start = clock();
		Sleep(99);
		finish = clock();
		cout << "2:"<<finish - start<<"ms"<< endl;//99ms
	}
	return 0;
}
    原文作者:宇宙379
    原文地址: https://blog.csdn.net/a379039233/article/details/111355446
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞