在 C++17 中以毫秒为单位获取时间?
Get time with milliseconds in C++17?
如何使用 boost 或标准库在 C++17 中获取以毫秒为单位的当前时间?我尝试使用 std::chrono:
int main()
{
const auto currentDateTime = std::chrono::system_clock::now();
const auto currentDateTimeTimeT = std::chrono::system_clock::to_time_t(currentDateTime);
const auto currentDateTimeLocalTime = *std::gmtime(¤tDateTimeTimeT);
char currentDateTimeArrStr[100];
std::strftime(currentDateTimeArrStr, 100, "%Y%m%d_%H%M%S.%f", ¤tDateTimeLocalTime);
std::clog << std::string(currentDateTimeArrStr) << std::endl;
}
但 %f
格式仅在 python strftime
函数中实现,而不是在 C++ 中实现,并且使用 boost:
int main()
{
const auto date = boost::gregorian::day_clock::universal_day();
boost::gregorian::date d(date.year(), date.month(), date.day());
const auto time = boost::posix_time::second_clock::universal_time().time_of_day();
boost::posix_time::time_duration td(time.hours(), time.minutes(), time.seconds(), time.fractional_seconds());
std::stringstream ss;
ss << d << ' ' << td;
boost::posix_time::ptime pt(not_a_date_time);
ss >> pt;
std::cout << pt << std::endl;
}
但是 boost api 只给 total_milliseconds
.
我需要这样的输出:12:02:34.323232
所以只打印从时间点算起的毫秒数...
const auto ms = std::chrono::time_point_cast<std::chrono::milliseconds>(currentDateTime).time_since_epoch().count() % 1000;
std::clog << std::put_time(¤tDateTimeLocalTime, "%Y%m%d_%H%M%S")
<< "." << std::setfill('0') << std::setw(3) << ms << std::endl;
How can i get current time with millisecond in C++11
您在 std::chrono::system_clock::now()
通话时已有当前时间。
如何使用 boost 或标准库在 C++17 中获取以毫秒为单位的当前时间?我尝试使用 std::chrono:
int main()
{
const auto currentDateTime = std::chrono::system_clock::now();
const auto currentDateTimeTimeT = std::chrono::system_clock::to_time_t(currentDateTime);
const auto currentDateTimeLocalTime = *std::gmtime(¤tDateTimeTimeT);
char currentDateTimeArrStr[100];
std::strftime(currentDateTimeArrStr, 100, "%Y%m%d_%H%M%S.%f", ¤tDateTimeLocalTime);
std::clog << std::string(currentDateTimeArrStr) << std::endl;
}
但 %f
格式仅在 python strftime
函数中实现,而不是在 C++ 中实现,并且使用 boost:
int main()
{
const auto date = boost::gregorian::day_clock::universal_day();
boost::gregorian::date d(date.year(), date.month(), date.day());
const auto time = boost::posix_time::second_clock::universal_time().time_of_day();
boost::posix_time::time_duration td(time.hours(), time.minutes(), time.seconds(), time.fractional_seconds());
std::stringstream ss;
ss << d << ' ' << td;
boost::posix_time::ptime pt(not_a_date_time);
ss >> pt;
std::cout << pt << std::endl;
}
但是 boost api 只给 total_milliseconds
.
我需要这样的输出:12:02:34.323232
所以只打印从时间点算起的毫秒数...
const auto ms = std::chrono::time_point_cast<std::chrono::milliseconds>(currentDateTime).time_since_epoch().count() % 1000;
std::clog << std::put_time(¤tDateTimeLocalTime, "%Y%m%d_%H%M%S")
<< "." << std::setfill('0') << std::setw(3) << ms << std::endl;
How can i get current time with millisecond in C++11
您在 std::chrono::system_clock::now()
通话时已有当前时间。