CSDN博客

img hustli

计算cpu速度的小程序

发表于2003/6/30 14:09:00  1422人阅读

分类: 编程中的小技巧

以下程序在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;
}
0 0

相关博文

我的热门文章

img
取 消
img