使用QueryPerformanceCounter()记录时间

#include <iostream>

using namespace std;

#ifdef _WIN32

#include<Windows.h>

class CTimer
{
private:

    LARGE_INTEGER m_base;
    LARGE_INTEGER m_temp;
    float m_resolution;

public:

    CTimer()
    {
        LARGE_INTEGER t_freq;
        QueryPerformanceFrequency(&t_freq);
        m_resolution = (float) (1.0f / (double) t_freq.QuadPart);
        reset();
    }

    void reset()
    {
        QueryPerformanceCounter(&m_base);
    }

    inline float GetCurrentTime() {
        QueryPerformanceCounter(&m_temp);
        return (m_temp.QuadPart - m_base.QuadPart) * m_resolution * 1000.0f;
    }

    void SleepTime(float ms_val){
        float ms_st = GetCurrentTime();
        while (GetCurrentTime()-ms_st < ms_val)
            continue;
    }

};
#else
class CTimer
{
private:
    unsigned long m_base;
public:
    CTimer() {
        reset();
    }

    void reset() {
        timeval t;
        gettimeofday(&t, NULL);
        m_base = t.tv_sec;
    }

    float GetCurrentTime() {
        timeval t;
        gettimeofday(&t, NULL);
        return 1000 * (t.tv_sec - m_base) + t.tv_usec * 0.001f;
    }
};
#endif

void test1()
{
    CTimer t;

    for (int i = 0; i < 100; ++i)
        cout << i << ' ';
    cout << endl;

    cout << t.GetCurrentTime() << endl;
}

void test2()
{
    CTimer t;

    for (int i = 0; i < 100; i++)
        cout << i << ' ';
    cout << endl;

    cout << t.GetCurrentTime() << endl;
}

int main()
{
    test1();
    test2();
    return 0;
}
用于测试某一段代码的运行时间(总数):
class CSTimer
{
private:
 	 LARGE_INTEGER 	 _tstartcount;
 	 LARGE_INTEGER 	 _time;
 	 float 			 _resolution;
 	 int 				 _ncount;
 	 bool 			 _ispaused;
public:
 	 CSTimer()
 	 {
 		 LARGE_INTEGER t_freq;
 		 QueryPerformanceFrequency(&t_freq);
 		 _resolution = (float) (1.0f / (double) t_freq.QuadPart);
 		 reset();
 	 }

 	 void reset()
 	 {
 		 _ncount = 0;
 		 _ispaused = true;
 		 QueryPerformanceCounter(&_tstartcount);
 		 _time.QuadPart = 0;
 	 }

 	 inline int count()
 	 {
 		 return _ncount;
 	 }

 	 inline float time() {
 		 return (_time.QuadPart) * _resolution * 1000.0f;
 	 }

 	 void pause() {
 		 if(!_ispaused)
 		 {
 			 LARGE_INTEGER time;
 			 QueryPerformanceCounter(&time);
 			 _time.QuadPart += time.QuadPart - _tstartcount.QuadPart;
 			 _ispaused = true;
 			 _ncount++;
 		 }
 	 }

 	 void resume() {
 		 if(_ispaused)
 		 {
 			 QueryPerformanceCounter(&_tstartcount);
 			 _ispaused = false;
 		 }
 	 }
};

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值