服务器开发

几种获取系统时间戳方式的对比

2019-05-24  本文已影响4人  夏楚子悦

1、std::chrono::system_clock::now()

std::chrono::system_clock::now().time_since_epoch().count();

2、std::chrono::steady_clock::now()

std::chrono::steady_clock::now().time_since_epoch().count();

3、gettimeofday

static inline uint64_t getCurrentMicroseconds(){
    struct timeval tv;
    gettimeofday(&tv, NULL);
    return tv.tv_sec * 1000000 + tv.tv_usec;
}

4、性能对比

static inline uint64_t getCurrentMicroseconds(){
    struct timeval tv;
    gettimeofday(&tv, NULL);
    return tv.tv_sec * 1000000 + tv.tv_usec;
}

class TimeIncPrinter{
public:
    TimeIncPrinter(){
        _start = getCurrentMicroseconds();
    }
    ~TimeIncPrinter(){
        cout << (getCurrentMicroseconds() - _start) / 1000 << endl;
    }

private:
    uint64_t _start;
};
int main() {    
    auto s0 = std::chrono::system_clock::now().time_since_epoch().count();
    auto s1 = std::chrono::steady_clock::now().time_since_epoch().count();
    auto s2 = getCurrentMicroseconds();
    uint64_t ret;
    cout << s0 << " " << s1 << " " << s2 << endl;
    {
        TimeIncPrinter printer;
        for(int i = 0; i < 1000 * 10000; ++i){
            ret = std::chrono::system_clock::now().time_since_epoch().count();
        }
    }

    {
        TimeIncPrinter printer;
        for(int i = 0; i < 1000 * 10000; ++i) {
            ret = std::chrono::steady_clock::now().time_since_epoch().count();
        }
    }

    {
        TimeIncPrinter printer;
        for(int i = 0; i < 1000 * 10000; ++i) {
            ret = getCurrentMicroseconds();
        }
    }

    auto e0 = std::chrono::system_clock::now().time_since_epoch().count();
    auto e1 = std::chrono::steady_clock::now().time_since_epoch().count();
    auto e2 = getCurrentMicroseconds();

    cout << e0 - s0 << " " << e1 - s1 << " " << e2 - s2 << endl;
    return 0 ;
}
xzldeMacBook-Pro:ZLToolKit xzl$ ./test_stamp
1558682596593660 20122625880580 1558682596593667
377
420
276
1073752 1073741548 1073746

5、测试总结

上一篇下一篇

猜你喜欢

热点阅读