C ++中的高分辨率计时器

时间:2013-08-09 13:15:57

标签: c++ unix

我正在阅读高分辨率计时器以检查给定功能所花费的时间。我找到了以下代码

double apHiResElapsedTime::sec () const
{
  struct timeval t;
  gettimeofday (&t, 0);

  double now = 1.e-6 * t.tv_usec + t.tv_sec;

  return (now - starting_);
}

我的问题1.e-6的价值在这里意味着什么? 为什么作者正在做1.e-6 * t.tv_usec + t.tv_sec。

在此请求您的帮助。

感谢您的时间和帮助。

1 个答案:

答案 0 :(得分:6)

1.e-6scientific notation中的数字,等于10 ^ -60.000001,且类型为double。您可以将其读作“十到六 - ”。

由于gettimeofday()将时间返回为两个单独的整数 - 秒和微秒,因此微秒部分将通过将整数微秒值除以百万来转换为表示秒的双精度值。然后,将整秒(tv_sec)添加到结果中。

例如,假设gettimeofday()返回6秒和5微秒,此代码将执行5 * 0.000001 + 6并产生6.000005秒。

另一方面,gettimeofday()并不是真正的高分辨率时钟(当然与定时器没有任何关系),它也被弃用了。您应该考虑使用clock_gettime()。它支持各种类型的“时钟”,并且能够达到纳秒精度。对于性能测量,人们倾向于使用CLOCK_MONOTONIC_RAW标志来访问非NTP调整的挂钟。请注意,它可能并非在所有系统上都可用。例如,在OS X上,必须使用mach_absolute_time()

我还建议避免使用FPU(float,double类型)。只需坚持使用两个整数即可。例如,如果您使用clock_gettime(),则可以计算不带双精度的差异。这是C99中一个非常简单的例子(我相信你可以轻松地将它转换为C ++):

//
// C99 program that demonstrates the usage of `clock_gettime()`
// and shows how to calculate a difference between two timestamps
// in nanoseconds.
//
// $ gcc -Wall -pedantic -std=gnu99 ./test.c -o ./test -lrt
//

#include <time.h>
#include <inttypes.h>
#include <stdio.h>

static int64_t
get_elapsed_time(const struct timespec * restrict start_time,
                 const struct timespec * restrict end_time)
{
    int64_t sec = end_time->tv_sec - start_time->tv_sec;
    int64_t nsec;
    if (end_time->tv_nsec >= start_time->tv_nsec) {
        nsec = end_time->tv_nsec - start_time->tv_nsec;
    } else {
        nsec = 1000000000 - (start_time->tv_nsec - end_time->tv_nsec);
        sec -= 1;
    }
    return sec > 0 ? sec * 1000000000 : 0 + nsec > 0 ? nsec : 0;
}

int main()
{
    struct timespec start_time;
    struct timespec end_time;

    clock_gettime(CLOCK_MONOTONIC_RAW, &start_time);
    puts("Hello!\n");
    clock_gettime(CLOCK_MONOTONIC_RAW, &end_time);
    printf("Oh, look! It took me %" PRId64 " nanoseconds to say hi!\n",
           get_elapsed_time(&start_time, &end_time));
}

希望它有所帮助。祝你好运!