c++打印封装每次打印前面加上时间戳问题
目录
- c++打印封装每次打印前面加上时间戳
- c++获取、打印当前时间:time、localtime
- 先来总结下
- 最后
c++打印封装每次打印前面加上时间戳
封装之后我们打印不必每次都加上时间
#include <IOStream>
#include <time.h>
#include <sys/time.h>
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
#include <string>
#include <mutex>
#include <pthread.h>
#include <threadandroid>
#include <unistd.h>
std::mutex g_mtx;
void printfTime()
{
char buf[32] = {0};
struct timeval tv;
struct tm tm;
size_t javascript len = 28;
memset(&tv, 0, sizeof(tv));
memset(&tm, 0, sizeof(tm));
gettimeofday(&tv, NULL);
localtime_r(&tv.tv_sec, &tm);
strftime(buf, len, "%Y-%m-%d %H:%M:%S", &tm);
len = strlen(buf);
sprintf(buf + len, ".%-6.3d", (int)(tv.tv_usec/1000));
printf("%s",buf);
}
void printXX()
{
std::cout<<std::endl;
}
template <typename T,typename... types>
void printXX(const T& firstArg,const types&... arges)
{
std::cout<<firstArg;
printXX(arges...);
}
templatphpe <typename T,typename... types>
void mvPrintf(const T& firstArg,const types&a编程客栈mp;... arges)
{
std::lock_guard<std::mutex> lock(g_mtx);
printfTime();
printXX(firstArg,arges...);
}
int main()
{
int i = 0;
std::string a="ddddd";
mvPrintf("i = ", i, " a = ",a);
i = 1000;
mvPrintf("i = ", i, " a = ",a);
mvPrintf("ssssssssssssssssssssssssssssssss ");
return 0;
}
输出:

c++获取、打印当前时间:time、localtime
先来总结下
1、函数1为基本的获取time_t格式时间函数;
2、函数3、4为转换为tm格式时间函数;
3、函数2、5、6为输出可读格式时间函数。
4、其中函数2、5不符合使用习惯,因此不长使用,常用函数6定制化输出。
以下函数全部在#include <ctime>中。
1、time_t time(time_t *seconds):
函数描述:返回基于当前系统的自纪元起经过的时间,以秒为单位。
参数/返回值: seconds,存储获取的时间。
使用:
time_t now = time(nullptr);
2、char *ctime(const time_t *timer):
函数描述:返回一个表示时间的字符串。
格式:
Www Mmm dd hh:mm:ss yyyy(Mon Apr 05 15:23:17 2021)
其中,Www表示星期,Mmm表示月份,dd表示天数,hh:mm:ss表示时间,yyyy表示年份。
参数:time_t类型的指针。
返回值: c字符串,包含可读格式的日期时间信息。
使用:
char* curr_time = ctime(&now); cout << curr_time <<endl; // Mon Apr 05 15:23:17 2021
3、struct tm *localtime(const time_t *timer):
函数描述:使用timer的值来填充tm结构。
参数:time_t类型的指针。
返回值: 返回指向tm结构的指针,本地时间。

使用:
tm* curr_tm = localtime(&now);
4、struct tm *gmtime(const time_t *timer):
函数描述:使用timer的值来填充tm结构。
参数:time_t类型的指针。
返回值: 返回指向tm结构的指针,GMT时间。
使用:
tm* curr_tm = gmtime(&now);
5、char *asctime(const struct tm *timeptr):
函数描述:将tm结构体表示的时间返回为可读的字符串类型。
参数:tm结构体类型的指针。
返回值: c字符串,包含可读格式的日期时间信息。
使用:
char* curr_time2 = asctime(curr_tm);
注:函数2 = 函数3/4 + 函数5; // 函数2实现的功能与3/4+5实现的一致。
6、size_t strftime(char *str, size_t maxsize, const char *format, const struct tm *timeptr):
函数描述:根据 format 中定义的格式化规则,格式化结构 timeptr 表示的时间,并把它存储在 str 中。
参数:
- str:这是指向目标数组的指针,用来复制产生的 C 字符串。
- maxsize:这是被复制到 strjs 的最大字符数。
- format:指定的 C 格式字符串。
使用:
time_t now = time(nullptr);
tm* curr_tm = localtime(&now); // 返回的结构体存储位置未知,不知何时释放,因此推荐使用安全版本。
char time[80] = {0};
strftime(time, 80, "%Y-%m-%d %H:%M:%S", curr_tm);
最后
以上为个人经验,希望能给大家一个参考,也希望大家多多支持编程客栈(www.devze.com)。
加载中,请稍侯......
精彩评论