我正在编写一个C代码,需要访问一个使用timeval作为当前时间表示的旧C库.
在旧包中获取我们使用的当前日期/时间:
struct timeval dateTime; gettimeofday(&dateTime,NULL); function(dateTime); // The function will do its task
现在我需要使用C计时器,如:
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);
后来在代码中我需要返回的方式,从返回的struct timeval构建一个time_point变量:
struct timeval dateTime; function(&dateTime); system_clock::time_point returnedDateTime = ?? // Help appreacited
我使用C11.
解决方法
[编辑为使用time_val而不是free 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;
在duration_cast中使用std :: chrono :: microseconds,并相应地调整您的(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) ;