[英]Get current time in milliseconds, or HH:MM:SS:MMM format
I've written a c++ function to get the current time in HH:MM:SS
format.我编写了一个 C++ 函数来以HH:MM:SS
格式获取当前时间。 How can I add milliseconds or nanoseconds, so I can have a format like HH:MM:SS:MMM
?如何添加毫秒或纳秒,以便我可以使用类似HH:MM:SS:MMM
的格式? If not possible, a function that returns current time in ms would also be good.如果不可能,以毫秒为单位返回当前时间的函数也很好。 I can then calculate the relative time distances between two log points myself.然后我可以自己计算两个日志点之间的相对时间距离。
string get_time()
{
time_t t = time(0); // get time now
struct tm * now = localtime(&t);
std::stringstream sstm;
sstm << (now->tm_hour) << ':' << (now->tm_min) << ':' << now->tm_sec;
string s = sstm.str();
return s;
}
This is a portable method using the C++11
chrono library:这是使用C++11
chrono 库的可移植方法:
#include <chrono>
#include <ctime>
#include <iomanip>
#include <sstream>
#include <string>
// ...
std::string time_in_HH_MM_SS_MMM()
{
using namespace std::chrono;
// get current time
auto now = system_clock::now();
// get number of milliseconds for the current second
// (remainder after division into seconds)
auto ms = duration_cast<milliseconds>(now.time_since_epoch()) % 1000;
// convert to std::time_t in order to convert to std::tm (broken time)
auto timer = system_clock::to_time_t(now);
// convert to broken time
std::tm bt = *std::localtime(&timer);
std::ostringstream oss;
oss << std::put_time(&bt, "%H:%M:%S"); // HH:MM:SS
oss << '.' << std::setfill('0') << std::setw(3) << ms.count();
return oss.str();
}
For windows maybe:对于窗户,也许:
#include <iostream>
#include <Windows.h>
#include <strsafe.h>
int main()
{
CHAR sysTimeStr[13] = {};
SYSTEMTIME systemTime;
GetLocalTime(&systemTime);
sprintf_s(sysTimeStr,
"%u:%02u:%02u:%03u",
systemTime.wHour,
systemTime.wMinute,
systemTime.wSecond,
systemTime.wMilliseconds);
std::cout << sysTimeStr;
}
Instead of using time()
(seconds since the epoch), try gettimeofday()
.不要使用time()
(自纪元以来的秒数),而是尝试gettimeofday()
。 Gives you a structure that includes a microseconds field.为您提供一个包含微秒字段的结构。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.