- 语言经验 - 《c++11获取系统时间最快的方式》

本文详细介绍了在C++中通过clock_gettime、gettimeofday和chrono获取时间的性能对比,特别是在百万级QPS服务场景下,强调了在Linux内核2.6之后gettimeofday的优化以及多线程对性能的影响。
摘要由CSDN通过智能技术生成

         本文属于专栏《构建工业级QPS百万级服务》系列简介-CSDN博客


1、结论

         c++11中获取unix时间最快的方式是clock_gettime和gettimeofday函数。

2、结论补充说明:

  • 在linux内核版本2.6之前,VDSO内核机制还没有引入时,gettimeofday需要在内核态与用户态之间切换,所以一些老的资料中,会让用户建立一个自己的时间缓存,但现在不需要了。
  • 单线程和多线程对时间获取的性能无影响,单线程可获取3000万次/秒,两个线程就可获取6000万次/秒。因为时间数据已经做到读写分离。当然,由于环境差异,会导致时间有差别,快速测试可使用文章后面的代码。

3、环境说明和测试代码:

        代码运行在32核linux机器,g++版本4.85,系统版本centos7。在我的测试环境中,单核clock_gettime、gettimeofday为3000万次/秒,chrono为1000万次/秒。(chrono慢的原因在《使用google profiler 对c++应用进行性能热点分析》中示例中可以了解到)

        编译命令 g++ test.cpp -std=c++11 -pthread

#include <iostream>
#include <chrono>
#include <ctime>
#include <sys/time.h>
#include <thread>
#include <vector>
#include <functional>

using namespace std;
using namespace std::chrono;

const int TEST_TIMES = 1000 * 1000 * 10;

long long getCurrentTimeByClockGetTime() {
    struct timespec spec;
    clock_gettime(CLOCK_REALTIME, &spec);
    return spec.tv_sec * 1000LL + spec.tv_nsec / 1000000;
}

long long getCurrentTimeByGetTimeOfDay() {
    struct timeval tv;
    gettimeofday(&tv, NULL);
    return tv.tv_sec * 1000LL + tv.tv_usec / 1000;
}

long long getCurrentTimeByChrono() {
    return duration_cast<milliseconds>(high_resolution_clock::now().time_since_epoch()).count();
}

void testFunction(const std::function<void()>& testFunc, const std::string& testName) {
    long long start = getCurrentTimeByChrono();
    for (int i = 0; i < TEST_TIMES; ++i) {
        testFunc();
    }
    long long end = getCurrentTimeByChrono();
    cout << "Using " << testName << " in thread " << this_thread::get_id() << ": " << end - start << " ms\n";
}

void testMultiThread(int thread_num, const std::function<void()>& testFunc, const std::string& testName) {
    vector<thread> threads;
    for (int i = 0; i < thread_num; ++i) {
        threads.emplace_back(testFunction, testFunc, testName);
    }
    for (auto& t : threads) {
        t.join();
    }
}

int main() {
    testMultiThread(1, getCurrentTimeByChrono, "chrono::high_resolution_clock");
    testMultiThread(10, getCurrentTimeByChrono, "chrono::high_resolution_clock");
    testMultiThread(1, getCurrentTimeByGetTimeOfDay, "gettimeofday");
    testMultiThread(10, getCurrentTimeByGetTimeOfDay, "gettimeofday");
    testMultiThread(1, getCurrentTimeByClockGetTime, "clock_gettime");
    testMultiThread(10, getCurrentTimeByClockGetTime, "clock_gettime");
}
  • 11
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值