以前写的一段计算cpu主频的代码,考虑到了某些cpu的负载平衡能力。
#include <stdlib.h> #include <stdio.h> #include <stdbool.h> #include <math.h> #include <windows.h> static ULONGLONG g_pf_s,g_pf_e,g_sys_freq = {0}; static ULONGLONG g_cycle_s,g_cycle_passed; //使CPU进入最高性能状态 WINAPI DWORD busy(PVOID param){for(;;);} inline ULONGLONG rdtsc(void) { ULONG hi,lo; __asm__ __volatile__("rdtsc;movl %%edx,%0;movl %%eax,%1":"=m"(hi),"=m"(lo)); return (ULONGLONG)hi<<32 | lo; } void get_sys_freq(void) { QueryPerformanceFrequency((PLARGE_INTEGER)&g_sys_freq); } static void start(void) { QueryPerformanceCounter((PLARGE_INTEGER)&g_pf_s); g_cycle_s = rdtsc(); } static void end(void) { g_cycle_passed = rdtsc() - g_cycle_s; QueryPerformanceCounter((PLARGE_INTEGER)&g_pf_e); } static void sh_cpu_pf(ULONG *pmhz,double *pmhz_dbl) { //实计算际经历的时间 ULONGLONG act_time_passed = (g_pf_e - g_pf_s) * 1000 / g_sys_freq; ULONG mhz = g_cycle_passed/act_time_passed/1000; double mhz_dbl = (double)g_cycle_passed/act_time_passed/1000; printf("sleep act time is %f ms,CPU is %f(%u) MHz\n",(double)act_time_passed,\ mhz_dbl,(unsigned)mhz); *pmhz=mhz;*pmhz_dbl=mhz_dbl; } typedef struct _pf_item { ULONG mhz; double mhz_dbl; }pf_item,*ppf_item; int main(int argc,char *argv[]) { pf_item pf_ary[32]; //将本线程优先级提升到最高以增加测量精度 SetThreadPriority(GetCurrentThread(),THREAD_PRIORITY_HIGHEST); get_sys_freq(); DWORD tid; CreateThread(NULL,0,busy,0,0,&tid); Sleep(1000); ULONGLONG mhz_total = 0; double mhz_dbl_total = 0.0f; for(int i = 0;i<32;i++) { start(); Sleep(500); end(); sh_cpu_pf(&pf_ary[i].mhz,&pf_ary[i].mhz_dbl); mhz_total += pf_ary[i].mhz; mhz_dbl_total += pf_ary[i].mhz_dbl; } printf("\nLast mhz : %f(%u)\n",mhz_dbl_total/32,(ULONGLONG)floor(mhz_dbl_total/32+0.5)); return 0; }