Unsigned long behaviour?

Why do I get the following output.

unsigned long foo, bar;

void setup() 
{
  
  Serial.begin(115200);
  delay(5000);
  foo = millis();
  Serial.println(foo);
  bar = millis();
  Serial.println(bar);
}

void loop()
{
  // put your main code here, to run repeatedly: 
  
}
Output

4999
5000

Firstly shouldnt the first value of the output be at least 5000 if there is a 5s delay before it. Also
shoulnt a line or several lines of code be executed faster than 1ms?

Also when testing longs I sometimes have the following random problem,

startOfMotorR: 1258291200
startOfMotorR: 1258291200
startOfMotorL: 5008
startOfMotorL: 5009
startOfMotorL: 5009

where it should look like,

startOfMotorL: 5008
startOfMotorL: 5008
startOfMotorL: 5009
startOfMotorR: 5009
startOfMotorL: 5009
startOfMotorR: 5009

eg. I m trying to record the start time of two motors and the unsigned longs are acting kind of funny. The full code is lengthy but Im simply just doing something similar in the example of just calling the millis function when i detect the encoders for the motors.

romarshmallow:
(...)
Also shoulnt a line or several lines of code be executed faster than 1ms?
(...)

Why?

romarshmallow:
Also shoulnt a line or several lines of code be executed faster than 1ms?

That depends on what the line of code does. Serial.print() is a slow function because it has to do a lot of stuff.

Can you create a demo program that illustrates the print anomalies ?

...R

I believe you see 4999 because the count is zero-relative. 5000 is actually 5 secs + 1 ms.

--Michael

The rolling over from 4999 to 5000 happened between the two print statements, which
says nothing at all about the time the code took other than it was less than 2ms. The
interrupt that increments millis() can happen at any point (where interrupts are enabled).

In actual fact millis isn't that well behaved, it sometimes steps by 2, rather than 1, as the
interrupt driving it actually runs at 1024Hz, not 1000Hz.

You can look at the code for millis() and the timer0 ISR if you want to figure out
exactly what happened, this is an open-source system. In fact you are encouraged to
do so!