簡體   English   中英

如何測量C代碼的運行時間比較?

[英]How can i measure running time comparison of C code?

示例代碼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];
}

我需要計算這些代碼塊的運行時間。 是否有任何工具(基准)來計算?

如果您在包含它的系統下運行,則可以在一定time下執行它:

$ time ./benchmark1

$ time ./benchmark2
#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;
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM