Calculate the execution time for the following piece of AVR assembly code given that the code will be running on an Atmel AVR 8-bit microcontroller being clocked by a 4MHz oscillator.
LDI R16, 5 Again: LDI R17, 4 Here: DEC R17 NOP BRNE Here DEC R16 NOP BRNE Again NOP NOP
Step 1 - Determine the Period (T)
Step 2 - Determine Total Number of Cycles for execution (C)
; Instruction # cycles to execute LDI R16, 5 ; 1 Again: LDI R17, 4 ;---------| Here: DEC R17 ;---| | NOP ; |B | BRNE Here ;---| | A DEC R16 ; | NOP ; | BRNE Again ;---------| NOP ; 1 NOP ; 1 ; _______________________________________________________ ; Total # of cycles for execution (C) = 3 + A
The total number of cycles for the execution of the code is given as (3 + A). In calculating the total number of cycles for execution, in this case, it must be taken into consideration that the blocks of code labeled A and B are executed more than once because they form loops.
What is done here is that we look at the block of code which construct the loops as a single instruction for which we will determine the number of cycle for execution next.
Calculating the number of cycles for block A
; Instruction # cycles to execute Again: LDI R17, 4 ; 1 Here: DEC R17 ;---| NOP ; | B BRNE Here ;---| DEC R16 ; 1 NOP ; 1 BRNE Again ; 2 ; _______________________________________________________ ; Total # of cycles for execution (C) = 5*(1+B+1+1+2) - 1
In this code the loop is controlled by the value in R16 which is 5. So the code in block A is done 5 times. This result in the number of cycles to execute code block A = 5(1+B+1+1+2) - 1= (5B + 24)cycles.
One important point to note here is that the BRNE instruction takes 2 cycle to execute when it is true and 1 cycle when the condition is false. So for the 5 times the BRNE instruction is executed 1 time the condition is false which is why we subtract 1.
Calculating the number of cycles for block B
; Instruction # cycles to execute Here: DEC R17 ; 1 NOP ; 1 BRNE Here ; 2 ; _______________________________________________________ ; Total # of cycles for execution (C) = 4*(1+1+2) - 1
In this code the loop is controlled by the value in R17 which is 4. So the code in block B is done 4 times. This result in number of cycle to execute code block B = 4*(1+1+2) - 1 = 15cycles . This futher implies that C = 3 + [5(15) + 24] = 102cycles.
Step 3 - Calculate Execution Time (ET) using information from steps 1 & 2
AVR Tutorials hopes this AVR assembly tutorial on calculating execution time was beneficial to you and looks forward to your continued visits for all your microcontroller tutorial needs.