Precision of the micros() function

Does anybody know the precision of the micros() function. I have been testing with a very tight loop and no matter what I have in the loop, the shortest time difference between 1 loop iteration and the next is about 1000 microseconds.

unsigned long long  tval1;
unsigned long long  tval2;
unsigned long       diff;

void setup() {
    Serial.begin(9600);
  
    Particle.variable("_diff",&diff,INT);
    tval1 = micros();
}
    void loop() {
    
    tval2 = micros();
    diff = tval2-tval1;

    tval1=tval2;
}

Not sure if this helps: https://docs.particle.io/reference/firmware/photon/#system-cycle-counter

1 Like

@jbstcyr, it is important to note that when loop() ends, the system firmware will do a bunch of housekeeping then run loop() again. This is unlike an Arduino which essentially just runs loop and nothing else. Another thing to note is that FreeRTOS which runs on the both the Photon and Electron has a minimum slice time of 1ms meaning that loop() will be called, at most, every millisecond. :wink:

2 Likes

Even Arduino does things in between iterations of loop() - e.g. SerialEvent() functions are serviced between iteration.

So in fact loop() is not a loop at all but only a function that gets called as part of the system main while(1) { ... }.

If you want to test a tight loop without "any" interference, you'd need to use SYSTEM_MODE(MANUAL) and a proper loop and also only take your measurements and calculate the avg time once you dropped out of that loop.

2 Likes

Thanks for all the info. I’ll look into it deeper.