No announcement yet.

Code Execution Time

  • Filter
  • Time
  • Show
Clear All
new posts

  • Code Execution Time

    Many people want a list of how long each PBP statement takes to execute.

    Unfortunately, there is no such list because it depends on the PIC chip being used, where the code is located in program memory, what bank the variables are in, and what size variable is being used. All the bank switching and code page changing takes time too.

    However, it's pretty easy to actually measure the time it takes to execute any block of statements. This saves you from having to add them all up anyways if you're finding the time for a block of code.

    Since a timer set to 1:1 prescaler uses FOSC/4, each tick represents the time it takes to execute 1 instruction cycle.

    So you can simply zero the timer and then turn it on just before the statements you want to time. Then turn it off immediately after those statements. The value in the timer will indicate the number of cycles used. You can then convert that to uSeconds if needed fairly easily by multiplying * 1/(OSC*1000000/4).

    Here's an example of measuring the time to do a 16/16 bit divide. But you can have any number of statements inbetween, as long as the time does not exceed 65535 instructions. This example uses the hardware serial port to send the results to a computer running a terminal program, but the results can just as easily be displayed on an LCD, or saved to EEPROM to be read back by a programmer.
    T1CON = 0                 ' Prescaler = 1:1,  Timer off
    @  MOVE?CB  OSC, _PicOSC  ; Get OSC value, for Time calculation
    W1        var word
    W2        var word
    Dummy  var word
    W1 = 12345
    W2 = 12
    ' -----  Measure Time for 16/16-bit variable divide -----
    Gosub ClearTimer1:
    @ bsf     T1CON, TMR1ON   ' Start timer
    Dummy = W1/W2               ' The statement to measure
    @ bcf     T1CON, TMR1ON   ' Stop timer
    Hserout ["16/16 Var divide= "] : Gosub ShowTime
    PicOSC     Var Byte
    Cycles     Var Word
    Period     Var Word
    Time       Var Word
         TMR1H = 0
         TMR1L = 0
         Cycles.lowbyte  = TMR1L
         Cycles.highbyte = TMR1H
         Period = 1000 / PicOSC * 4 / 10   ' Time for 1 Instruction Cycle in 100ns
         Time = Cycles * Period
         Time = Div32 10
         Hserout [ Dec Cycles, "   ",Dec Time/10, ".", Dec Time//10," uS", 13,10]
    @ 20Mhz, the result for this is 382 instructions or 76.4uS

    Another method (if you own an oscilloscope) is to simply set a pin HIGH before executing the code, then setting the pin LOW immediately afterwards and measure the pulse width on an oscilloscope.
    PBP3 Manual : Microchip Datasheets - 10F, 12F, 16F, 18F
    Never download a PIC datasheet from anywhere but