高精度纳秒计时器

 ///
// 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);
    }   
};

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值