ISR execution

Does anyone know the time it takes just to enter and exit an GPIO ISR? Finding the time it takes to execute the code within is almost trivial, however, i am having trouble finding information on how long it takes the arduino to save context and restore context before and after the ISR is executed? Is there some resource for this information somewhere that I am missing?

ATmega328P datasheet…

7.7.1 Interrupt Response Time

The interrupt execution response for all the enabled AVR interrupts is four clock cycles minimum. After four clock cycles the program vector address for the actual interrupt handling routine is executed. During this four clock cycle period, the Program Counter is pushed onto the Stack. The vector is normally a jump to the interrupt routine, and this jump takes three clock cycles. If an interrupt occurs during execution of a multi-cycle instruction, this instruction is completed before the interrupt is served. If an interrupt occurs when the MCU is in sleep mode, the interrupt execution response time is increased by four clock cycles. This increase comes in addition to the start-up time from the selected sleep mode.

A return from an interrupt handling routine takes four clock cycles. During these four clock cycles, the Program Counter (two bytes) is popped back from the Stack, the Stack Pointer is incremented by two, and the I-bit in SREG is set.

Holy cow I feel like a moron the datasheet did not even occur to me :fearful: Thank you very much that is incredibly helpful.

Finding the time it takes to execute the code within is almost trivial, however, i am having trouble finding information on how long it takes the arduino to save context

On the AVR, almost all of the context is saved/restored by the ISR code, rather than hardware. Note that you have to look at the code at the ISR vector and wrapper, not just the code in the function you provide as the argument to attachInterrupt(). The actual path looks something like:

foo_isr_vector: jmp foo_isr_wrapper
   :
foo_isr_wrapper:
  ;; save ISR context
    call user_function
  ;; restore ISR context
  iret

user_function:
  ;; save C context
    code
  ;; restore C context
  ret

IIRC we decided that 2-3uS was common, I think Nick Gammon did some tests.

But you can use ISR_NAKED (sp?) and do your own context save if you really need speed.


Rob