C++时间戳

文章介绍了如何使用C++11的chrono库的high_resolution_clock进行纳秒级计时,以及传统gettimeofday获取微秒级时间,通过Benchmark框架测试两者在不同迭代次数下的性能差异。
摘要由CSDN通过智能技术生成

时延打点

1、chrono的std::chrono::high_resolution_clock::now() 可以到纳秒

2、gettimeofday() 到微秒us

/* Get the current time of day and timezone information,
   putting it into *TV and *TZ.  If TZ is NULL, *TZ is not filled.
   Returns 0 on success, -1 on errors.
   NOTE: This form of timezone information is obsolete.
   Use the functions and variables declared in <time.h> instead.  */
extern int gettimeofday (struct timeval *__restrict __tv,
			 __timezone_ptr_t __tz) __THROW __nonnull ((1));

使用

#include "../3th/include/benchmark/benchmark.h"
#include<chrono>
#include <sys/time.h>

using namespace std;
using namespace chrono;

static void recordTimeByChrono(benchmark::State& state)
{
    typedef std::chrono::high_resolution_clock Clock;
    for (auto _ : state)
    {
        auto t1 = Clock::now();//计时开始
        // do something
        auto t2 = Clock::now();//计时结束
        std::chrono::duration_cast<std::chrono::nanoseconds>(t2 - t1).count();
        // std::chrono::duration_cast<std::chrono::microseconds>(t2 - t1).count();
    }
}
BENCHMARK(recordTimeByChrono)->Iterations(100000);
BENCHMARK(recordTimeByChrono)->Iterations(10000);
BENCHMARK(recordTimeByChrono)->Iterations(1000);
BENCHMARK(recordTimeByChrono)->Iterations(100);

static void recordTimeByGettimeofday(benchmark::State& state)
{
    for (auto _ : state)
    {
        struct timeval t1;
        struct timeval t2;

        gettimeofday(&t1,NULL);
        // do something
        gettimeofday(&t2,NULL);
        (t2.tv_sec - t1.tv_sec)*1000000 + t2.tv_usec-t1.tv_usec;
    }
}
BENCHMARK(recordTimeByGettimeofday)->Iterations(100000);
BENCHMARK(recordTimeByGettimeofday)->Iterations(10000);
BENCHMARK(recordTimeByGettimeofday)->Iterations(1000);
BENCHMARK(recordTimeByGettimeofday)->Iterations(100);

性能

在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值