【问题标题】:C++ timer in microseconds以微秒为单位的 C++ 计时器
【发布时间】:2014-04-20 18:36:57
【问题描述】:

我试图在微秒内做一个计时器,但它不太有效。

#include <time.h>
#include <iostream>
#include <unistd.h>

using namespace std;

int main ()
{
    struct timespec start_time;
    struct timespec end_time;
    clock_gettime(CLOCK_PROCESS_CPUTIME_ID, &start_time);
    usleep(5000);
    clock_gettime(CLOCK_PROCESS_CPUTIME_ID, &end_time);
    cout << "START: " << (start_time.tv_nsec/1000) << endl;
    cout << "END: " << (end_time.tv_nsec/1000) << endl;
    cout << "DIFF: " << (end_time.tv_nsec - start_time.tv_nsec) /1000 << endl;

    return 0;
}

结果如下:

START: 3586
END: 3630
DIFF: 43

我需要 DIFF 在 5000 左右。有什么建议吗?

【问题讨论】:

  • 有一个标准的&lt;chrono&gt; 标头。不需要特定于平台的代码。
  • @chris:不过,仅从 C++11 开始。

标签: c++ time timer


【解决方案1】:

我不确定您要测量什么,但我猜CLOCK_PROCESS_CPUTIME_ID 是错误的计时器,如果您想测量经过的时间,您可能需要CLOCK_MONOTONIC。看看similar stackoverflow question,它显示了clock_gettime 的不同时钟之间的差异。

也就是说,要获得全部时间,您必须在每次测量中添加 tv_sectv_nsec(当然首先将 tv_sec 转换为纳秒),然后减去该总数,例如:

uint64_t startNs = start_time.tv_sec * 1000 * 1000 * 1000 + start_time.tv_nsec;
uint64_t endNs = end_time.tv_sec * 1000 * 1000 * 1000 + end_time.tv_nsec;
uint64_t diffNs = endNs - startNs;
uint64_t diffMicro = diffNs / 1000;

如果您使用 C++11,最好使用 chrono 命名空间中的一些 high level class

【讨论】:

  • 我认为您可能处于溢出领域。这就是结构有两个部分的原因
【解决方案2】:

两件事。

  1. 猜你需要 CLOCK_REALTIME
  2. timespec 有两个组成部分 - 进行减法时需要同时考虑这两个组成部分

【讨论】:

    【解决方案3】:

    试试 clock_gettime(CLOCK_REALTIME, &start) clock_gettime(CLOCK_REALTIME, &stop)

    您还需要使用 timespec 结构的“tv_sec”部分。

    时间 = ((stop.tv_sec - start.tv_sec)+ (double)(stop.tv_nsec - start.tv_nsec)/1e9)*1000;//im ms

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-03-12
      • 2015-08-31
      • 1970-01-01
      • 1970-01-01
      • 2014-06-24
      • 1970-01-01
      • 2017-07-10
      • 2016-02-14
      相关资源
      最近更新 更多