C++ gettimeofday() 返回相同的值

标签 c++ c time gettimeofday

/*
 * 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 时间戳?

最佳答案

floatbetween 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/

相关文章:

c++ - 什么是横向指针转换?

c++ - CreateDirectory 不创建目录 VS2017 c++

c - C 的新手数学检查器。为什么它不起作用?

time - Lua 将格式 "X h X min"转换为 WoW 中的秒

language-agnostic - 1970 年之前的日期有何特别之处?

c++ - 是否可以定义 enumalpha?

c++ - SIOCGIWFREQ ioctl 返回错误 22 EINVAL - 参数无效,为什么?

c - 使用 c 从应用程序指示器中的 GtkMenu 中删除 GtkMenuItem

python - 从 Fortran/C 调用 Python 函数

firebase - Firestore 的 .info/serverTimeOffset?