Delays in C


Looking at compiled code to determine how many loops to execute to make a 1 ms delay


Here is the delay function:

void delay(int num)
{
    int i;

    while (num>0)       /* Out loop delays num ms */
    {
        i = 1333;       /* Inner loop takes 6 cycles */
        while (i > 0)   /* 1333 times 6 = 1 ms */
        {
            i = i-1;
        }
        num = num - 1;
    }
}
Here is the mahcine code:
                ; 27 void delay(int num)
                ; 28 {
                    switch  .text
0851            _delay:
0851 3b             pshd    
0852 3b             pshd    
     00000002   OFST:   set 2
0853 200d           bra L55
0855            L35:
                ; 33        i = 1333;   /* Inner loop takes 6 cycles */
0855 cd0535         ldy #1333
0858            L16:
                ; 36            i = i-1;
0858 03             dey 
0859 6d80           sty OFST-2,s
                ; 34        while (i > 0) 
085b 2efb           bgt L16
                ; 38        num = num - 1;
085d ed82           ldy OFST+0,s
085f 03             dey 
0860 6d82           sty OFST+0,s
0862            L55:
                ; 31    while (num>0)   /* Out loop delays num ms */
0862 ec82           ldd OFST+0,s
0864 2eef           bgt L35
                ; 40 }
0866 1b84           leas    4,s
0868 3d             rts 
                    xdef    _main
                    xdef    _delay
The inner loop consists of the three instructions:
0858         L16:       dey 
0859 6d80               sty OFST-2,s
085b 2efb               bgt L16
This takes 6 cycles. 1 ms is 8000 cycles, so to wait for 1 ms, execute this loop 8000/6 = 1333 times.