I set up a sketch to test the hz of the main loop with millis() vs micros().
With millis() hz was giving a reading between 288,935 and 289,232 but with micros is was reading 174,730 which is substantially slower. Is is just because the arduino has to deal with bigger numbers or because it has to update the number more frequently, or is it something completely different? Is there a way to count time in a faster way?
Edit: I should have specified that I am using a Nano
None. I used an unsigned long which holds a maximum of 4,294,967,295. That's a bigger number than the Arduino could have possibly counted to in 1 second seeing as it has a 16Mhz clock.
unsigned long millis()
{
unsigned long m;
uint8_t oldSREG = SREG;
// disable interrupts while we read timer0_millis or we might get an
// inconsistent value (e.g. in the middle of a write to timer0_millis)
cli();
m = timer0_millis;
SREG = oldSREG;
return m;
}
unsigned long micros() {
unsigned long m;
uint8_t oldSREG = SREG, t;
cli();
m = timer0_overflow_count;
#if defined(TCNT0)
t = TCNT0;
#elif defined(TCNT0L)
t = TCNT0L;
#else
#error TIMER 0 not defined
#endif
#ifdef TIFR0
if ((TIFR0 & _BV(TOV0)) && (t < 255))
m++;
#else
if ((TIFR & _BV(TOV0)) && (t < 255))
m++;
#endif
SREG = oldSREG;
return ((m << 8) + t) * (64 / clockCyclesPerMicrosecond());
}
In your case this is very visible because your loop does nothing but increment a counter, so that is very light compared to the overhead needed for micros()
Using a hardware timer would be the less intrusive way of measuring the time spent in the loop
The millis() function only reads the variables already accumulated by the Timer0 overflow ISR and just returns their values.
The micros() function reads the current counter value of Timer0 and calculates the elapsed time, because return value need even higher time resolution.
Therefore, the execution time of the micros() function is considerably longer than millis() function.
The difference is about 36 instruction cycles. I think most of that will be the micros() function but a little will be: if(timer >= 1000){
vs. if(timer >= 1000000){
In the millis() case you compare a 32-bit integer to a 16-bit constant and with the micros() case you compare a 32-bit integer to a 32-bit constant. I suspect the full 32-bit comparison takes more cycles.