实现一个精确到毫秒的计时器

2019-01-09  本文已影响0人  lixin_karl
#include <iostream>
#include <sys/time.h>
using namespace std;

class TimeTick{
public:
    bool first;
    unsigned long long _delay2msec;
    unsigned long long getCurrentMsec()
    {
        struct timeval tv;
        gettimeofday(&tv,nullptr);
        return tv.tv_sec * 1000 + tv.tv_usec / 1000;
    }
    bool operator ()(unsigned long long msec) {//毫秒
        if(first)
        {
            _delay2msec = getCurrentMsec() + msec;
            first = false;
            return true;
        }

        if(getCurrentMsec() >= _delay2msec)
        {
            _delay2msec =  getCurrentMsec()+ msec;
            return true;
        }
        return false;
    }
};
int main()
{
    TimeTick tt ;
    while(true)
    {
        while(tt(1000ULL))
        {
            cout<<"TimeTick"<<endl;
        }
    }
}
上一篇 下一篇

猜你喜欢

热点阅读