Good day!

Tell me, please, I’m puzzling for a couple of hours ... In the microC there is a function Delay_ms. For example, Delay_ms (11). It sets the delay to 11 milliseconds.
Clock frequency - 8 MHz. In assembly language, this instruction looks like this:

;Delay_ms(11); LDI R17, 115 LDI R16, 72 L_main8: DEC R16 BRNE L_main8 DEC R17 BRNE L_main8 

DEC performed 1 clock, BRNE - 1 clock, if there is no transition, 2 clock cycles, if there is. Now, if you count the number of ticks, you can find out the time (11 milliseconds).
I'm trying to count the number of ticks like this:

 ((1+2)*71 + 2) * 115 * (1+2) + 1 = 74 176 

Now, to find out the time delay, it is necessary to divide by the frequency:

 74 176 / 8*10^6 = 0,009272 = 9 мс 

Total, instead of 11 milliseconds, I get 9. Tell me, please, what did I lie to? I assume that there is an error in counting the number of cycles, but I do not see it.

    2 answers 2

    Hm As far as I understand, the inner loop has a length of 72 iterations only on the first iteration of the outer loop, right? All other iterations are driven from the maximum value of R16 .

    Update

    Wait, still have to take into account the remaining internal cycles! At the point L_main8 we get the following values ​​R16 and R17:

      72 115 71 115 ... 1 115 (проход во внешний цикл) 0 114 255 114 (или что получается из 0 после DEC?) 254 114 ... 1 114 0 113 

    etc.

    • @VladD, thanks for the reply! Then it turns out 72 * 3 + 115 * 5 = 791 ..? generally a very small number is obtained ... - Ice_Fox
    • @IceFox: Wait, you must also take into account the remaining internal cycles! At the point L_main8 , we get the following values: R16 and R17: 72 115 71 115 ... 1 115 (pass to the external cycle) 0 114 255 114 (or what is obtained from 0 after DEC?) 254 114 ... 1 114 0 113 and so on - VladD
     ;Delay_ms(11); LDI R17, 115 // 1 такт LDI R16, 72 // 1 такт L_main8: DEC R16 // цикл 1 - 1 такт BRNE L_main8 // цикл 1 - 2 такта DEC R17 // цикл 2 - 1 такт BRNE L_main8 // цикл 2 - 2 такта. 

    Let's calculate: the outer loop will run 115 times. On each cycle there will be one subtraction and one transition - a total of 3 clocks (the last iteration of 2 clocks) total 3 * 115 - 1 = 344 clocks. The inner loop will go through 72 iterations 3 * 72 - 1 = 215 for the first time and the remaining 114 times will go through 256 iterations (3 * 256 - 1) * 114 = 87 438 add 2 clocks to LDI, 2 + 344 + 215 + 87438 = 87999 = without 8800 cycles per cycle, i.e. 11 ms at 8 MHz