格式化输出当前时间

 近期在测试跨进程数据共享时需要测试延时情况,在不适用日志系统的情况下,我们要对别多个进程在数据读写的时刻的差值,为此需要记录各操作对应的时刻,使用uint64_4打印timestamp是一种可行的方式,但是看着还是别扭,于是采用亲和人眼的年月日时分秒的方式。

这段代码比较简单,做成一个函数后面使用吧,也供有需要的人使用。编译g++ test.cpp -o test即可。

#include <sys/time.h>
#include <stdio.h>
#include <iostream>
using namespace std;

/**
 * @brief 返回带有yyyy-mm-dd hh:MM:SS.MS格式的当前时刻对应的字符串,如果想使用us级别的,可以修改最后的tv.tv_usec部分
 * 
 * @return std::string 
 */
std::string formatCurrentTimeStr()
{
    std::string sTimestamp;
    char acTimestamp[256];

    struct timeval tv;
    struct tm *tm;

    gettimeofday(&tv, NULL);

    tm = localtime(&tv.tv_sec);

    sprintf(acTimestamp, "%04d-%02d-%02d %02d:%02d:%02d.%03d\
",
            tm->tm_year + 1900,
            tm->tm_mon + 1,
            tm->tm_mday,
            tm->tm_hour,
            tm->tm_min,
            tm->tm_sec,
            (int)(tv.tv_usec / 1000));

    sTimestamp = acTimestamp;

    return sTimestamp;
}

int main(void)
{
    std::cout << formatCurrentTimeStr() << std::endl;
    return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值