/*
* Returns time in s.usec
*/
float mtime()
{
struct timeval stime;
gettimeofday(&stime,0x0);
return (float)stime.tv_sec+((float)stime.tv_usec)/1000000000;
}
main(){
while(true){
cout<<setprecision(15)<<mtime()<<endl;
// shows the same time irregularly for some reason and can mess up triggers
usleep(500000);
}
}
为什么显示的时间不规律? (在ubuntu 64位和C++上编译) 还有哪些其他标准方法可用于生成毫秒精度的 unix 时间戳?
最佳答案
float
有 between 6 and 9 decimal digits of precision .
如果整数部分是例如1,391,432,494(我写这篇文章时的 UNIX 时间;需要 10 位数字),小数部分的数字已经用完了。不太好,这就是 float
失败的原因。
跳转至double gives you 15 digits因此,只要您可以假设整数部分是 UNIX 时间戳,即自 1970 年以来的秒数,似乎就足够了,因为这意味着它不太可能很快使用更多的数字。
关于C++ gettimeofday() 返回相同的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21527948/