当前位置导航:炫浪网>>网络学院>>编程开发>>C++教程>>C++进阶与实例

C++高精度定时器

 ///////////////////////////////////////////////////////////////////////////////
// KTimer.h
//
//      Windows Graphics Programming Win32 GDI and DirectDraw?
//      Feng Yuan 
//      Publisher: Prentice Hall PTR 
//      First Edition December 01, 2000
//
//  高精度纳秒计时器, 最后修改:
//      2008-12  by cheungmine@gmail.com
///////////////////////////////////////////////////////////////////////////////
/* Usage:

    int main()
    {
        KTimer  kt;
        unsigned int cpu_speed = kt.CPUSpeedMHz();

        kt.Start();

        Sleep(1234);

        unsigned int elapsed_cyc = (unsigned int) kt.Stop();

        printf("CPU Speed: %.2f Ghz. Elapsed %ld CPU Cycles ( %ld Nanosecond)n", 
            cpu_speed/1000.f, 
            elapsed_cyc, 
            KTimer::CyclesToNanos(elapsed_cyc, cpu_speed));
    }
*/
#pragma once

#ifndef STRICT
#  define STRICT
#endif

#ifndef WIN32_LEAN_AND_MEAN
#  define WIN32_LEAN_AND_MEAN
#endif

#include <windows.h>

inline unsigned __int64 GetCycleCount(void)
{
    _asm    _emit 0x0F
    _asm    _emit 0x31
}

class KTimer
{
    unsigned __int64  m_startcycle;

public:

    unsigned __int64  m_overhead;   // Clock Cycles

    KTimer(void)
    {
        m_overhead = 0;
        Start();
        m_overhead = Stop();
    }

    // 启动CPU时钟
    void Start(void)
    {
        m_startcycle = GetCycleCount();
    }

    // 停止CPU时钟, 返回自上一次启动的时钟周期数
    unsigned __int64 Stop(void)
    {
        return GetCycleCount()-m_startcycle-m_overhead;
    }

    // 把以CPU周期数转为纳秒
    unsigned __int64 static CyclesToNanos(unsigned __int64 time_cycles, unsigned int speed_mhz)
    {
        return time_cycles*1000 / speed_mhz;
    }
    
    // 把以CPU周期数转为毫秒
    unsigned __int64 static CyclesToMillis(unsigned __int64 time_cycles, unsigned int speed_mhz)
    {
        return time_cycles / speed_mhz / 1000;
    }

    // 1GHz = 1000MHz
    unsigned int CPUSpeedMHz()
    {
        Start();
        Sleep(1000);
        unsigned __int64 cputime = Stop();
        
        return (unsigned int)(cputime/1000000);
    }   
};

相关内容
赞助商链接