0
点赞
收藏
分享

微信扫一扫

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

爱写作的小土豆 2021-09-27 阅读 79

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

  • 功能:获取系统时间戳,单位微秒(microsecond)
  • 使用方法:
std::chrono::system_clock::now().time_since_epoch().count();

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

  • 功能:获取系统时间戳,单位纳秒(nanosecond)
  • 使用方法:
std::chrono::steady_clock::now().time_since_epoch().count();

3、gettimeofday

  • 功能:获取系统时间戳,单位微秒(microsecond)
  • 使用方法:
static inline uint64_t getCurrentMicroseconds(){
    struct timeval tv;
    gettimeofday(&tv, NULL);
    return tv.tv_sec * 1000000 + tv.tv_usec;
}

4、性能对比

  • 对比方式:每种获取时间戳方式运行1000万次,统计执行时间
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、测试总结

  • gettimeofday性能最佳,但是3种方式性能差距都不算很大。
  • gettimeofday返回值与std::chrono::system_clock::now()一致,可以完全替代gettimeofday。
  • 由于windows不支持gettimeofday函数,推荐获取时间戳使用std::chrono::system_clock::now()方式。
举报

相关推荐

0 条评论