Calculating time spent in a loop

Hi All,

My MCU is ATmega1608. I am trying to calculate the time spent in a while loop. The only reason to calculate time spent in the loop is to find out if my peripheral is stopped or not by polling the status bit of timer. If it is stopped than I have to set a flag. This peripheral is TCB in singleshot mode.

// ***** If counter is not running , wait for atleast one pulse to start ***** //

     while(!(TCB1.STATUS & TCB_RUN_bm))

I want to know how much time is spend in this loop. If my program does not come out of this while loop in 17us, then I have to set a flag. How to find how much time does this execution takes?

have you looked into micros() for keeping time in a loop?

I didn't get your point.

duh

loop()
{
unsigned long mymicros=micros();
while(1)
{

unsigned long tPast = micros()-mymicros;
if (tPast >= 17 )
{
then I'm screwed.
break;
}

}

}

That is not a complete while() loop since you do not show the body

unsigned long startTime = millis();
// reset your flag
while(!(TCB1.STATUS & TCB_RUN_bm)) {
  if ( millis() - startTime > 17 ) {
  // set your flag
  break;
}
...

Which header file has micros() definition?

The loop instructions themselves take 6 clock cycles. 0.375 microseconds. Maybe another cycle or two if the loop isn't empty.

Disassemble the code and count instruction cycles:

     while(!(TCB1.STATUS & TCB_RUN_bm))
   0:	80 91 97 0a 	lds	r24, 0x0A97	    ; get status: 3 cycles
   4:	80 ff       	sbrs	r24, 0      ; check the bit: 1 cycle if no skip.
   6:	fc cf       	rjmp	.-8      	; back to start of loop: 2 cycles

I suppose the interesting question is what is inside the loop. (If anything. It looks like one of those typically-empty "wait for a flag" loops.)

It is wait for a flag loop.