Compiler optimization snafu???

From: Charles Sullivan (cwsulliv_at_triad.rr.com)
Date: 11/28/05


Date: Mon, 28 Nov 2005 19:21:08 GMT

I need to calibrate a timing loop for a delay which is substantially
shorter than the resolution available with nanosleep().
 
Consider the short test program "loopcal.c" using alarm() which
follows. It works if compiled and executed like this:
$ gcc -Wall loopcal.c -o loopcal
$ ./loopcal
Beginning 1 second calibration.
Alarm flag = 0, Loop count = 61702367

But if compiled with the -O switch:
$ gcc -O -Wall loopcal.c -o loopcal
$ ./loopcal
Beginning 1 second calibration.
Alarm flag = 0, Loop count = 0
Calibration failed.

(After grinding away for about 20 seconds. It looks like the
compiler optimizer decided that the alarmflag could be ignored.)

Can anyone explain how to overcome this obstacle?

(The calibrate function is intended to be included in a larger
program which is compiled with the -O switch and which I'm
reluctant to change.)

Regards,
Charles Sullivan
================== loopcal.c ===================
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <signal.h>

/*--------------------------+
 | Timing loop calibration. |
 +--------------------------*/
static int alarmflag;

static void alarm_isr ()
{
   alarmflag = 0;
   return;
}

unsigned long loop_calibrate ( void )
{
   unsigned long count;

   alarmflag = 1;
   count = 0;
   signal(SIGALRM, alarm_isr);

   alarm(1);
   while ( alarmflag && ++count );
   alarm(0);

   return count;
}

int main ( void )
{
   unsigned long count;

   printf("Beginning 1 second calibration.\n");
   count = loop_calibrate();
   printf("Alarm flag = %d, Loop count = %lu\n",
         alarmflag, count);
   if ( count == 0 )
      printf("Calibration failed.\n");
   return 0;
}
================================================



Relevant Pages

  • Re: trim(string) problems
    ... >> Together these make me think it is a compiler problem ... >> but correctly finds size with both explicit and implicit ... that makes my test program with the module work and should ...
    (comp.lang.fortran)
  • Re: GDB Doesnt Recognize Core File Format
    ... The language I am using is C, the debugger and compiler ... the test program was C. ... I did not feel the request for information was anymore ... Future posts concerning ...
    (comp.lang.c)
  • Re: Indirect array addressing of optional parameters illegal?
    ... > using compiler optimisation rather than just debugging options. ... > The test program below causes a 100% reproducible bus error or ... here is the test program ... > end program IndirectAddressing ...
    (comp.lang.fortran)
  • Re: Checking endianess in compile time
    ... > unsigned int tffca: 1; ... > Is there a way to check if the compiler considers bitfield ten to be ... the above struct and an unsigned char, ... abort the build if the test program fails. ...
    (comp.lang.c)