5

我在 64 位 Ubuntu 12.04 系统上并尝试了以下代码:

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


int
main(void)
{
  struct timespec user1,user2;
  struct timespec sys1,sys2;
  double user_elapsed;
  double sys_elapsed;

  clock_gettime(CLOCK_REALTIME, &user1);
  clock_gettime(CLOCK_PROCESS_CPUTIME_ID, &sys1);
  sleep(10);
  clock_gettime(CLOCK_REALTIME, &user2);
  clock_gettime(CLOCK_PROCESS_CPUTIME_ID, &sys2);
  user_elapsed = user2.tv_sec + user2.tv_nsec/1E9;
  user_elapsed -= user1.tv_sec + user1.tv_nsec/1E9;
  printf("CLOCK_REALTIME: %f\n", user_elapsed);
  sys_elapsed = sys2.tv_sec + sys2.tv_nsec/1E9;
  sys_elapsed -= sys1.tv_sec + sys1.tv_nsec/1E9;
  printf("CLOCK_PROCESS_CPUTIME_ID: %f\n", sys_elapsed);
}

据我了解,这应该打印类似

CLOCK_REALTIME: 10.000117
CLOCK_PROCESS_CPUTIME_ID: 10.001

但就我而言,我得到的是

CLOCK_REALTIME: 10.000117
CLOCK_PROCESS_CPUTIME_ID: 0.000032

这是正确的行为吗?如果是这样,我如何确定 sys1 和 sys2 的实际秒数?

当我将 CLOCK_PROCESS_CPUTIME_ID 更改为 CLOCK_REALTIME 时,我得到了预期的结果,但这不是我想要的,因为我们需要精度。

[编辑] 显然 CLOCK_PROCESS_CPUTIME_ID 返回 cpu 用于处理的实际时间。CLOCK_MONOTONIC 似乎返回了正确的值。但精度如何?

4

1 回答 1

6

基本上,我们需要的只是精确地获得应用程序的当前运行时间(以微秒为单位)。

如果我没有误解,这里的运行时间是指经过的时间。通常,CLOCK_REALTIME这是有好处的,但如果时间是在应用程序运行期间设置的,则CLOCK_REALTIME经过时间的概念也会发生变化。为了防止这种情况发生 - 尽管它可能不太可能 - 我建议使用CLOCK_MONOTONIC或,如果存在,CLOCK_MONOTONIC_RAW. 从手册页中的描述

   CLOCK_REALTIME
          System-wide real-time clock.  Setting this clock requires appro-
          priate privileges.

   CLOCK_MONOTONIC
          Clock that cannot be set and  represents  monotonic  time  since
          some unspecified starting point.

   CLOCK_MONOTONIC_RAW (since Linux 2.6.28; Linux-specific)
          Similar  to  CLOCK_MONOTONIC, but provides access to a raw hard-
          ware-based time that is not subject to NTP adjustments.

CLOCK_MONOTONIC可能会受到 NTP 调整的影响,但CLOCK_MONOTONIC_RAW不是。所有这些时钟的分辨率通常为 1 纳秒(使用 进行检查clock_getres()),但出于您的目的,低于 1 微秒的分辨率就足够了。

以微秒为单位计算经过的时间

#define USED_CLOCK CLOCK_MONOTONIC // CLOCK_MONOTONIC_RAW if available
#define NANOS 1000000000LL

int main(int argc, char *argv[]) {
    /* Whatever */
    struct timespec begin, current;
    long long start, elapsed, microseconds;
    /* set up start time data */
    if (clock_gettime(USED_CLOCK, &begin)) {
        /* Oops, getting clock time failed */
        exit(EXIT_FAILURE);
    }
    /* Start time in nanoseconds */
    start = begin.tv_sec*NANOS + begin.tv_nsec;

    /* Do something interesting */

    /* get elapsed time */
    if (clock_gettime(USED_CLOCK, &current)) {
        /* getting clock time failed, what now? */
        exit(EXIT_FAILURE);
    }
    /* Elapsed time in nanoseconds */
    elapsed = current.tv_sec*NANOS + current.tv_nsec - start;
    microseconds = elapsed / 1000 + (elapsed % 1000 >= 500); // round up halves

    /* Display time in microseconds or something */

    return EXIT_SUCCESS;
}
于 2012-08-10T14:09:22.107 回答