code optimization help

05 Feb 2010

i have a piece of code that uses the timer function and is activated on an interrupt signal, i understand that any calculation done will increase total time to execute. what i need help doing is finding the best way to order the code to get the most accurate time.

here a snippet of the code im using:

 

void trigger() { //interrupt function
    end = timer.read_ms();
    single_spin = end - begin;
    
//write time to file
    FILE *fp = fopen("/local/out.csv", "a");
    count = count + 1;
    fprintf(fp, "%d, %.2d\n", count, single_spin);
    fclose(fp);

    begin = timer.read_ms();
}


int main() {
    timer.start();
    w.rise(&trigger);

//then main program

i have done some fiddling with it but im open to suggestions on how to run this code more accurately

05 Feb 2010

Doing any long work in the interrupt handler is a bad idea. Especially opening and writing to a file. Interrupt handler should be as short and fast as possible.

As I understand, you want to measure times between interrupts. What I think you should do is just set the flag in the interrupt, and handle it in the main loop. For example:

bool got_interrupt;
void trigger()
{
  got_interrupt = true;
}
...
int main()
{
  got_interrupt = false;
  FILE *fp = fopen("/local/out.csv", "w");
  int count = 1;
  begin = timer.read_ms();
  while (1)
  {
    if ( got_interrupt )
    {
      got_interrupt = false;
      end = timer.read_ms();
      fprintf(fp, "%d %.2d\n", count, end - begin);
      fflush(fp);
      begin = end;
    }
    // do other work
    __WFI(); // wait for interrupt
  }
  fclose(fp);
}

This won't work very well if file writing or other processing in the main loop takes longer than time between interrupts. In that case you could, for example, make an list of timestamps, add entries to it in the handler and pop them in main loop. That will need some means of synchronizing access to the list...

05 Feb 2010

And don't forget to use "volatile"

 

volatile bool got_interrupt;

It will tell the compiler not to remove the read from the while loop in optimization effort.

 

09 Feb 2010 . Edited: 10 Feb 2010

hey thanks Igor and llya, i will need to do the second option you suggested as there is a lot of slow processes / calculations taking place in the main loop and the interrupts are happening on average every 30ms ( well that's what im getting from my code unoptimised )  the main problem will be the synchronisation, that or i can calculate the time it takes to open and write to a file and deduct that from the final time... its all going to be a bit of a work around.