计算cpu速度的小程序

王朝vc·作者佚名  2006-01-08
窄屏简体版  字體: |||超大  

以下程序在vc60,console方式下编译运行通过。大家可以试一试,很准的说。

#include <stdio.h>

#include <windows.h>

float measure_clock_speed();

int main(void)

{

printf("The cpu is running in %f MHz",measure_clock_speed());

getchar();

return 1;

}

float measure_clock_speed ()

//-------------------------------------

{

unsigned long ticks;

unsigned long cycles;

unsigned long stamp0,

stamp1;

unsigned long freq = 0;

unsigned long freq2 =0;

unsigned long freq3 =0;

unsigned long total;

unsigned long tries=0;

LARGE_INTEGER t0,t1;

LARGE_INTEGER count_freq;

if (!QueryPerformanceFrequency( &count_freq ) )

{

return 0.0f;

}

unsigned long priority_class = GetPriorityClass(GetCurrentProcess());

long thread_priority = GetThreadPriority(GetCurrentThread());

SetPriorityClass(GetCurrentProcess(), REALTIME_PRIORITY_CLASS);

SetThreadPriority(GetCurrentThread(), THREAD_PRIORITY_TIME_CRITICAL);

do

{

tries++;

freq3 = freq2;

freq2 = freq;

QueryPerformanceCounter(&t0);

t1.LowPart = t0.LowPart;

t1.HighPart = t0.HighPart;

while ( (unsigned long)t1.LowPart - (unsigned long)t0.LowPart<50)

{

QueryPerformanceCounter(&t1);

}

_asm

{

rdtsc

mov stamp0, EAX

}

t0.LowPart = t1.LowPart; // Reset Initial

t0.HighPart = t1.HighPart; // Time

while ((unsigned long)t1.LowPart-(unsigned long)t0.LowPart<1000 )

{

QueryPerformanceCounter(&t1);

}

_asm

{

rdtsc

mov stamp1, EAX

}

cycles = stamp1 - stamp0;

ticks = (unsigned long) t1.LowPart - (unsigned long) t0.LowPart;

ticks = ticks * 100000;

ticks = ticks / ( count_freq.LowPart/10 );

if ( ticks%count_freq.LowPart > count_freq.LowPart/2 )

{

ticks++; // Round up if necessary

}

freq = cycles/ticks; // Cycles / us = MHz

if ( cycles%ticks > ticks/2 )

{

freq++; // Round up if necessary

}

total = ( freq + freq2 + freq3 );

} while ( (tries < 3 ) || (tries < 20) && ((abs(3 * freq -total) > 3)

||

(abs(3 * freq2-total) > 3) || (abs(3 * freq3-total) > 3)));

if ( total / 3 != ( total + 1 ) / 3 )

{

total ++; // Round up if necessary

}

// restore the thread priority

SetPriorityClass(GetCurrentProcess(), priority_class);

SetThreadPriority(GetCurrentThread(), thread_priority);

return float(total) / 3.0f;

}

 
 
 
免责声明:本文为网络用户发布,其观点仅代表作者个人观点,与本站无关,本站仅提供信息存储服务。文中陈述内容未经本站证实,其真实性、完整性、及时性本站不作任何保证或承诺,请读者仅作参考,并请自行核实相关内容。
 
 
© 2005- 王朝網路 版權所有  導航