Search code examples
cdead-code

Dead coding in C


Im analyzing the following code with different options of the compiler (O0 O1 O2 O3 Os). First of the iterations is out of the loop for "warming the cache". With O0 and O1 the time of ejecutions is different of 0.00 being higher as the input parameters (N and ITER) are bigger.

The problem arrives when I use O2, O3 and Os options. The time of ejecution is 0.000. I have read and possibly it is a dead code detection. Is it possible? And why is it happening?

  for(i=0; i<N; i++){
    a = i * 128;
    b = a / 32;
  }

  gettimeofday(&inicio, NULL);

  for(j=0; j<ITER; j++)
   for(i=0; i<N; i++){
     a = i * 128;
     b = a / 32;
   }

  gettimeofday(&final, NULL);

  tiempo = (final.tv_sec-inicio.tv_sec + (final.tv_usec-inicio.tv_usec)/1.e6);
  fprintf(fp,"%lf\n",tiempo);
  printf("%lf\t",tiempo);

  for(i=0; i<N; i++){
     a = i << 7;
     b = a >> 5;
   }

  gettimeofday(&inicio, NULL);

  for(j=0; j<ITER; j++)
   for(i=0; i<N; i++){
     a = i << 7;
     b = a >> 5;
   }

Could anyone help me? Thanks


Solution

  • Since the variables involved in the computation are not accessed outside the loop, it would not surprise me that the compiler is removing the code entirely.

    Two easy ways to check:

    1. Declare a and b as volatile.
    2. Take a look at the resulting assembly from different optimization levels.