ミリ秒単位のタイマ

boost::timer が秒単位しか対応していなかったので自作した。
時間の取得は、QueryPerformanceCounter() を使用しているので、
Windows 以外だと動きません。
Linux?ナニソレ美味しいの。

#include <assert.h>
#include <windows.h>

#include "timer.hpp"

int
main(){
    
    kmt_ex::ms_timer    timer;
    Sleep(24);

    // ms_timer のコンストラクタが呼ばれた時間からの差分を返してる
    double after = timer.elapsed();
    assert(static_cast<int>(after) == 24);

    // リスタート
    timer.restart();
    Sleep(55);
    assert(static_cast<int>( timer.elapsed() ) == 55);

    return 0;
}

使い勝手は、boost::timer とそんなに変わらないはず。
若干、処理のタイムラグがあるので、環境によっては assert() でエラーが出るかも知れない。
そういえば、資料調べてる時に気づいたけど、chrono ライブラリの存在をすっかり忘れてた。
あとで試してみよう。
追記:やってみました

[参照]
http://msdn.microsoft.com/ja-jp/library/cc410966.aspx
http://www14.big.or.jp/~ken1/tech/tech19.html

以下、timer.hpp のソースコード

#ifndef _KMT_EX_TIMER_H_
#define _KMT_EX_TIMER_H_

#include <boost/rational.hpp>

namespace kmt_ex{

typedef boost::rational<time_t> clock_t;

#ifdef _WIN32

#include <windows.h>
#pragma comment(lib, "winmm.lib")
#include <mmsystem.h>

/**
    std::clock() のミリ秒版
    Windowsのみ対応
*/
struct clock_impl{
    
    clock_impl() : frequency_(0){
        get_frequency();
    }

    clock_t operator ()() const{
        LARGE_INTEGER    rerformance;
        if( QueryPerformanceCounter(&rerformance) == FALSE){
            rerformance.QuadPart = 0;
        }
        return rerformance.QuadPart / frequency_ * 1000;
    }

    void get_frequency(){
        LARGE_INTEGER    rerformance = {0};
        if(QueryPerformanceFrequency(&rerformance) == FALSE){
            rerformance.QuadPart = 0;
        }
        frequency_ = rerformance.QuadPart;
    }
    
private:
    clock_t    frequency_;
};
static const clock_impl    clock;

#endif


/**
    boost::timer のミリ秒版
    使い勝手はほぼ同じ
*/
struct ms_timer{
    
    ms_timer() : start_time(0){
        restart();
    }

    double elapsed() const{
        return boost::rational_cast<double>(clock() - start_time);
    }

    void restart(){
        start_time = clock();
    }

private:
    clock_t    start_time;
};

}        // namespace kmt_ex


#endif