-1

I am trying to measure how much time takes serial program to reverse an array. My code:

#include <time.h>

int main() {
   int n = 100000;
   int c, d, a[n], b[n];
   clock_t start, end;

   for (c = 0; c < n ; c++)
      a[c] = c;

   start = clock();

   for (c = n - 1, d = 0; c >= 0; c--, d++)
      b[d] = a[c];

   end = clock();
   printf("Number of seconds: %f\n", (end-start)/(double)CLOCKS_PER_SEC );

   return 0;
}

However, it is always takes 0.000000 seconds to run. Why? If I increase n, I get segmentation errors.

zavg
  • 10,351
  • 4
  • 44
  • 67
Bob
  • 10,427
  • 24
  • 63
  • 71
  • You should be aware that this does not reverse your array as you reverse twice! Think about (for example) the first iteration which reverse c=n-1, d=0 and the last iteration which reverse c=0, d=n-1... – Jean-Baptiste Yunès Jan 03 '15 at 17:50

2 Answers2

3

The loop:

   for (c = n - 1, d = 0; c >= 0; c--, d++)
      b[d] = a[c];

is optimized out by your compiler. Your compiler figured out b and a are not further used in your program.

To avoid the compiler optimizing out the loop you can pass b and a as arguments to a dummy external function. You could also use volatile qualifiers but this is likely to bias your result.

ouah
  • 142,963
  • 15
  • 272
  • 331
3

Try many iterations:

#include <time.h>

int main() {
int n = 100000;
int c, d, a[n], b[n];
clock_t start, end;
start = clock();
for(int i =0; i< 100000000;i++) {
  for (c = 0; c < n ; c++)
   a[c] = c;
for (c = n - 1, d = 0; c >= 0; c--, d++)
  b[d] = a[c];
}
end = clock();
printf("Number of seconds: %f\n", (end-start)/(double)CLOCKS_PER_SEC/100000000 );
return 0;
}

but better read this: C++ clock stays zero

Community
  • 1
  • 1
maxpovver
  • 1,580
  • 14
  • 25