如何测量C代码的运行时间比较?

时间:2012-01-31 18:49:56

标签: c++ c time-complexity

示例代码1:

const int N=100000;

for(int j=0;j<N;j++){
    arr1[j] += a1[j];
    arr2[j] += a2[j];
}

示例代码2:

for(int j=0;j<N;j++){
    arr1[j] += a1[j];
}
for(int j=0;j<N;j++){
    arr2[j] += a2[j];
}

我需要计算这些代码块的运行时间。是否有任何工具(基准)来计算它?

2 个答案:

答案 0 :(得分:5)

如果你在包含它的系统下运行,你可以在time下执行它:

$ time ./benchmark1

$ time ./benchmark2

答案 1 :(得分:1)

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

const int N=100000;

void time_first() {
  struct timeval start, mid, end;
  long mtime, seconds, useconds;    

  gettimeofday(&start, NULL);
  for(int j=0;j<N;j++){
    arr1[j] += a1[j];
    arr2[j] += a2[j];
  }  
  gettimeofday(&end, NULL);

  seconds  = end.tv_sec  - start.tv_sec;
  useconds = end.tv_usec - start.tv_usec;

  mtime = ((seconds) * 1000 + useconds/1000.0) + 0.5;

  printf("First elapsed time: %ld milliseconds\n", mtime);
}

void time_second() {
  struct timeval start, mid, end;
  long mtime, seconds, useconds;    

  gettimeofday(&start, NULL);
  for(int j=0;j<N;j++){
    arr1[j] += a1[j];
  }
  for(int j=0;j<N;j++){
    arr2[j] += a2[j];
  }
  gettimeofday(&end, NULL);

  seconds  = end.tv_sec  - start.tv_sec;
  useconds = end.tv_usec - start.tv_usec;

  mtime = ((seconds) * 1000 + useconds/1000.0) + 0.5;

  printf("Second elapsed time: %ld milliseconds\n", mtime);
}

int main() {
  initialize arr1, a1 and a2

  time_first();
  time_second();
  return 0;
}