c/c++语言开发共享以C为单位获取当前时间(以毫秒为单位)?

在C中Java的System.currentTimeMillis()的等价性是什么?

    在Linux和其他类Unix系统上,你应该使用clock_gettime(CLOCK_MONOTONIC) 。 如果这不可用(例如Linux 2.4),您可以回退到gettimeofday() 。 后者具有受时钟调整影响的缺点。

    在Windows上,您可以使用QueryPerformanceCounter() 。

    我的这段代码将上述所有内容抽象为一个简单的接口,返回毫秒数作为int64_t。 请注意,返回的毫秒值仅用于相对使用(例如超时),并且与任何特定时间无关。

    检查time.h ,可能类似于gettimeofday()函数。

    你可以做点什么

     struct timeval now; gettimeofday(&now, NULL); 

    然后,您可以通过从now.tv_secnow.tv_usec获取值来提取时间。

    有time()函数,但它返回秒,而不是毫秒。 如果需要更高的精度,可以使用特定于平台的函数,如Windows的GetSystemTimeAsFileTime()或* nix的gettimeofday() 。

    如果你实际上并不关心日期和时间,而只想计算两个事件之间的时间间隔,如下所示:

     long time1 = System.currentTimeMillis(); // ... do something that takes a while ... long time2 = System.currentTimeMillis(); long elapsedMS = time2 - time1; 

    那么C等价物是clock() 。 在Windows上,为此目的使用GetTickCount()更为常见。

    请参阅此主题: http : //cboard.cprogramming.com/c-programming/51247-current-system-time-milliseconds.html

    它说time()函数精确到秒,更精确的需要其他库…

     #include  /** * @brief provide same output with the native function in java called * currentTimeMillis(). */ int64_t currentTimeMillis() { struct timeval time; gettimeofday(&time, NULL); int64_t s1 = (int64_t)(time.tv_sec) * 1000; int64_t s2 = (time.tv_usec / 1000); return s1 + s2; } 

    我像Java中的System.currentTimeMillis()一样编写这个函数,它们具有相同的输出。

      以上就是c/c++开发分享以C为单位获取当前时间(以毫秒为单位)?相关内容,想了解更多C/C++开发(异常处理)及C/C++游戏开发关注计算机技术网(www.ctvol.com)!)。

      本文来自网络收集,不代表计算机技术网立场,如涉及侵权请联系管理员删除。

      ctvol管理联系方式QQ:251552304

      本文章地址:https://www.ctvol.com/c-cdevelopment/545820.html

      (0)
      上一篇 2021年1月10日
      下一篇 2021年1月10日

      精彩推荐