我正在编写一个C++代码,该代码需要访问使用timeval表示当前时间的旧C库。
在旧包中,我们使用了当前日期/时间:
struct timeval dateTime;
gettimeofday(&dateTime, NULL);
function(dateTime); // The function will do its task
现在,我需要使用C++ chrono,如下所示:
system_clock::time_point now = system_clock::now();
struct timeval dateTime;
dateTime.tv_sec = ???? // Help appreaciated here
dateTime.tv_usec = ???? // Help appreaciated here
function(dateTime);
在后面的代码中,我需要回溯,从返回的
time_point
构建struct timeval
变量: struct timeval dateTime;
function(&dateTime);
system_clock::time_point returnedDateTime = ?? // Help appreacited
我正在使用C++ 11。
最佳答案
[编辑为使用time_val
而不是免费的vars]
假设您以毫秒的精度相信自己的system_clock
,可以这样进行:
struct timeval dest;
auto now=std::chrono::system_clock::now();
auto millisecs=
std::chrono::duration_cast<std::chrono::milliseconds>(
now.time_since_epoch()
);;
dest.tv_sec=millisecs.count()/1000;
dest.tv_usec=(millisecs.count()%1000)*1000;
std::cout << "s:" << dest.tv_sec << " usec:" << dest.tv_usec << std::endl;
在
std::chrono::microseconds
中使用duration_cast
并相应地调整您的(div/mod)代码以提高精度-请注意您对获得的值的准确性的信任程度。转换回为:
timeval src;
// again, trusting the value with only milliseconds accuracy
using dest_timepoint_type=std::chrono::time_point<
std::chrono::system_clock, std::chrono::milliseconds
>;
dest_timepoint_type converted{
std::chrono::milliseconds{
src.tv_sec*1000+src.tv_usec/1000
}
};
// this is to make sure the converted timepoint is indistinguishable by one
// issued by the system_clock
std::chrono::system_clock::time_point recovered =
std::chrono::time_point_cast<std::chrono::system_clock::duration>(converted)
;
关于c++ - 将std::chrono::system_clock::time_point转换为struct timeval并返回,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/39421089/