https://en.reddit.com/r/arduino/comm..._clock_cycles/
Timer0 interrupts every millisecond and may cause jitter in your timer1 measurement. Timer0 is used for millis() and micros()
you can also look at the assembler code the compiler generates (.lst).
a simple TIMER1 cycle counting sketch
Code:
// cycle counter using timer 1
volatile unsigned int t1, t2;
void setup()
{
unsigned long result;
unsigned int i, mint, maxt;
Serial.begin(9600); while (!Serial);
TCCR1A = 0;// set registers to 0
TCCR1B = 0;
TCCR1C = 0;
TCNT1 = 0;
TCCR1B = 1;// start timer 1
TCCR1B = 0; //stop the timer
t2 = TCNT1; //store passed ticks
Serial.print("res ");
Serial.println(t2);
TCNT1 = 0;
TCCR1B = 1;// start timer 1
asm volatile("nop");
asm volatile("nop");
asm volatile("nop");
asm volatile("nop");
TCCR1B = 0; //stop the timer
t2 = TCNT1; //store passed ticks
Serial.print("4 nops ");
Serial.println(t2);
TCNT1 = 0;
TCCR1B = 1;// start timer 1
result = millis();
TCCR1B = 0; //stop the timer
t2 = TCNT1; //store passed ticks
Serial.print("millis ");
Serial.println(t2);
analogRead(A0);
analogRead(A0);
TCNT1 = 0;
TCCR1B = 1;// start timer 1
i = analogRead(A0);
TCCR1B = 0; //stop the timer
t2 = TCNT1; //store passed ticks
Serial.print("ADC ");
Serial.println(t2);
}
void loop() {}
Code:
TCNT1 = 0;
25e: 10 92 85 00 sts 0x0085, r1 ; 0x800085 <__TEXT_REGION_LENGTH__+0x7e0085>
262: 10 92 84 00 sts 0x0084, r1 ; 0x800084 <__TEXT_REGION_LENGTH__+0x7e0084>
TCCR1B = 1;// start timer 1
266: c0 93 81 00 sts 0x0081, r28 ; 0x800081 <__TEXT_REGION_LENGTH__+0x7e0081>
...
asm volatile("nop");
asm volatile("nop");
asm volatile("nop");
asm volatile("nop");
TCCR1B = 0; //stop the timer
272: 10 92 81 00 sts 0x0081, r1 ; 0x800081 <__TEXT_REGION_LENGTH__+0x7e0081>
t2 = TCNT1; //store passed ticks
276: 80 91 84 00 lds r24, 0x0084 ; 0x800084 <__TEXT_REGION_LENGTH__+0x7e0084>
27a: 90 91 85 00 lds r25, 0x0085 ; 0x800085 <__TEXT_REGION_LENGTH__+0x7e0085>