Thern
Thern

Reputation: 1059

How long does this function take?

I am trying to figure out how long this assembly function takes on an Atmel ATmega162. The original code comments and namings suggest that it should create a delay of 10 µs, but I have my doubts about that. Unfortunately, I am inexperienced with assembly code, so I am not sure if my assumptions are correct.

Here is the code:

Timer_Loop_10us:

push Counter

ldi Counter,5
timer_wait10us:
nop
dec Counter
tst Counter
brne timer_wait10us

pop Counter
ret

According to the ATmega specifications, ldi, nop, dec, and tst take 1 clock cycle. push and pop take 2 cycles, ret takes 4 cycles, and brne takes 1 or 2 cycles. I suppose that it takes 1 cycle if Counter = 0 and 2 cycles if Counter != 0 because of the necessary jump back to the label, but I am not sure about that.

So if I am correct, the whole function takes 33 clock cycles. The ATmega162 has a CPU speed of 16 MHz, which means that this function would just create a delay of 2 µs, not 10µs.

Am I right or do I miss something here?

Upvotes: 2

Views: 406

Answers (1)

Thern
Thern

Reputation: 1059

I think I have understood the issue thanks to the comments of Martin Rosenau.

Indeed the clock frequency is not 16 MHz on my device, but 3.6864 MHz. And the call function also needs to be taken into account. Like the return function, it needs 4 cycles to be executed. So we have not 33, but 37 clock cycles at a speed of 3.6864 MHz, which quite exactly yields 10 µs for the operation.

Thanks for the help!

Upvotes: 2

Related Questions