CPU时间始终为零:(

时间:2012-05-01 03:10:52

标签: c++ c time cpu

我正在尝试使用以下代码测量CPU时间。

timespec time1, time2, temp_time;

clock_gettime(CLOCK_PROCESS_CPUTIME_ID, &time1);
 int i;
 int cpu_sum = 0;


 for (i = 0; i < nelements; i++) {

  cpu_sum += array[i];

 }    
clock_gettime(CLOCK_PROCESS_CPUTIME_ID, &time2);
temp_time.tv_sec = time2.tv_sec - time1.tv_sec;
printf( sum: %d using CPU in %lf ms \n",cpu_sum, temp_time.tv_sec);

但我总是把时间花在0.000ms上 知道这里有什么问题。

任何帮助都将不胜感激。

由于

4 个答案:

答案 0 :(得分:4)

  1. 您通过将错误的参数类型传递给printf time_t(可能是long而不是double)来调用未定义的行为。< / p>

  2. tv_sec只包含整个秒的部分时间。您还需要使用tv_nsec来获取纳秒部分。

  3. 尝试类似:

    temp_time.tv_sec = time2.tv_sec - time1.tv_sec;
    temp_time.tv_nsec = time2.tv_nsec - time2.tv_nsec;
    if (temp_time.tv_nsec < 0) {
        temp_time.tv_nsec += 1000000000;
        temp_time.tv_sec--;
    }
    printf("%lld.%.9ld\n", (long long)temp_time.tv_sec, (long)temp_time.tv_nsec);
    

答案 1 :(得分:1)

以上不会按原样编译,但有一个明显的问题:您只查看tv_sec字段而不是tv_nsec字段。测量整秒的两个tv_sec值可能是相同的,因为将花费不到一秒的CPU时间。

要减去两个timespec结构值(未经测试):

void ts_delta(struct timespec *result, struct timespec *a, struct timespec *b) {
    int borrow = 0;
    long n = a->tv_nsec - b->tv_nsec;

    if (n < 0) { /* nsec underflow; borrow 1 from seconds */
        n += 1000000000L;
        borrow = 1;
    }
    result->tv_nsec = n;
    result->tv_sec = a->tv_sec - b->tv_sec - borrow;
}

答案 2 :(得分:0)

我假设您正在尝试使用Linux。

在我的系统中,它打印如下。您可以查看并告诉我它是否有效。

ayub@gentux ~ $ cat cputime.c
#include <stdio.h>
#include <time.h>

int main(void)
{
  struct timespec time1, time2, temp_time;

  clock_gettime(CLOCK_PROCESS_CPUTIME_ID, &time1);
  int i;
  int cpu_sum = 0;
  static int array[1000]; /* 'static' to make the array initialized to zero by default (for demo) */
  int nelements = 1000;
  long diff = 0;

  array[0] = 10;
  for (i = 0; i < nelements; i++) {
    cpu_sum += array[i];
  }    
  clock_gettime(CLOCK_PROCESS_CPUTIME_ID, &time2);
  temp_time.tv_sec = time2.tv_sec - time1.tv_sec;
  temp_time.tv_nsec = time2.tv_nsec - time1.tv_nsec;
  diff = temp_time.tv_sec * 1000000000 + temp_time.tv_nsec; /* total ns */
  printf("Sum: %d using CPU in %lf ms \n", cpu_sum, (double) diff/1000000); /* now we print as milisecond */

  return 0;
}

ayub@gentux ~ $ gcc -o cputime cputime.c -lrt
ayub@gentux ~ $ time ./cputime
Sum: 10 using CPU in 0.003197 ms 

real    0m0.001s
user    0m0.000s
sys     0m0.000s
ayub@gentux ~ $ ./cputime 
Sum: 10 using CPU in 0.002599 ms

答案 3 :(得分:0)

gnu libc手册有一些很好的信息,甚至包括一个示例减法函数

http://www.gnu.org/software/libc/manual/html_node/Elapsed-Time.html

相关问题