【问题标题】:C++: How would I get unix time?C++:我将如何获得 unix 时间?
【发布时间】:2011-03-03 03:48:45
【问题描述】:

我需要一个函数或方法来在几秒钟内获得 UNIX 纪元,就像我在 PHP 中使用 time 函数一样。

我找不到任何方法,除了 ctime 中的 time() 似乎只输出格式化的日期,或者具有秒数但似乎总是 100 万的倍数的 clock() 函数,没有任何分辨率.

我想测量程序的执行时间,我只是想计算开始和结束之间的差异; C++ 程序员将如何做到这一点?

编辑:time() 和 difftime 只允许以秒为单位进行解析,而不是 ms 或其他任何东西。

【问题讨论】:

  • 您是否想要比秒精度更好但以秒为单位的测量值?
  • 你提出了不相关的要求。你说你想要以秒为单位的 unix epoch,你说你想要测量性能/执行时间。这两件事通常通过不同的方式实现。

标签: c++ unix time epoch


【解决方案1】:

time() 应该可以正常工作,使用difftime 进行时间差计算。如果您需要更好的解决方案,请使用gettimeofday

另外,复制:Calculating elapsed time in a C program in milliseconds

【讨论】:

    【解决方案2】:

    如果你想分析 get,我建议使用 getrusage。这将允许您跟踪 CPU 时间而不是挂钟时间:

    struct rusage ru;
    getrusage(RUSAGE_SELF, &ru);
    
    ru.ru_utime.tv_sec;  // seconds of user CPU time
    ru.ru_utime.tv_usec; // microseconds of user CPU time
    ru.ru_stime.tv_sec;  // seconds of system CPU time
    ru.ru_stime.tv_usec; // microseconds of system CPU time
    

    【讨论】:

      【解决方案3】:

      这段代码应该适合你。

      time_t epoch = time(0);


      #include <iostream>
      #include <ctime>
      using namespace std;
      
      int main() {
          time_t time = time(0);
          cout<<time<<endl;
          system("pause");
          return 0;
      }
      

      如果您有任何问题,请随时在下方发表评论。

      【讨论】:

        猜你喜欢
        • 2016-05-20
        • 1970-01-01
        • 2012-07-30
        • 1970-01-01
        • 2023-04-03
        • 2011-08-26
        • 1970-01-01
        • 2010-11-03
        相关资源
        最近更新 更多