C++获取时间戳 微秒级

std::string formatTimeStamp(long long microTimestamp)
{
	std::time_t seconds_since_epoch = static_cast(microTimestamp / 1000000);//将时长转换为秒
#if defined _MSC_VER && _MSC_VER >= 1400
	tm exact_time;
	localtime_s(&exact_time, &seconds_since_epoch);
	int tm_microsec = static_cast(microTimestamp % 1000);
	int tm_millisec = static_cast(microTimestamp / 1000 % 1000);
#elif defined __GNUC__
	tm exact_time;
	localtime_r(&seconds_since_epoch, &exact_time);
	int tm_microsec = static_cast(microseconds_since_epoch % 1000);
	int tm_millisec = static_cast(microseconds_since_epoch / 1000 % 1000);
#else
#error "Unknown compiler"
#endif
	char temp[27]{ 0 };
	snprintf(temp,
		27,
		"%04d-%02d-%02d %02d:%02d:%02d.%03d%03d",
		exact_time.tm_year + 1900,
		exact_time.tm_mon + 1,
		exact_time.tm_mday,
		exact_time.tm_hour,
		exact_time.tm_min,
		exact_time.tm_sec,
		tm_millisec,
		tm_microsec);
	return std::string(temp);
}
long long getMicroTimestamp() {
	auto duration_since_epoch = std::chrono::system_clock::now().time_since_epoch(); // 从1970-01-01 00:00:00到当前时间点的时长
	auto microseconds_since_epoch = std::chrono::duration_cast(duration_since_epoch).count(); // 将时长转换为微秒数
	return microseconds_since_epoch;
}

getMicroTimestamp用来获取微秒级时间戳,formatTimeStamp用来格式化输出时间格式。

你可能感兴趣的:(C++,杂记,c++,java,开发语言)