Cause of initial iteration of loop being slower than subsequent iterations.

Hi!

Primarily all of my coding experience is in MATLAB and it's been years since I've had a C++ course, so forgive my naivety.

I was wondering why when I output the time it takes to output a string to the serial monitor, the initial iteration always takes longer than all of the subsequent iterations.

I've experimented with this output in two ways:

(1)

int timekeep;
int i = 0;
void setup()

{
  Serial.begin(38400);
 
  while (i<10) {
      timekeep=millis();
      Serial.println("abitrary string");
      timekeep=millis()-timekeep;
      Serial.println("That took " + String(timekeep) + " milliseconds to write.");
      i= i + 1;
  }

}

void loop()
{
  //empty
}

and

(2)

int timekeep;

void setup()
{
  Serial.begin(38400);

}

void loop()
{
  timekeep=millis();
  Serial.println("arbitrary string");
  timekeep=millis()-timekeep;
  Serial.println("That took " + String(timekeep) + " miliseconds to write.");
}

I've satisfied my intended goal with both programs, but my curiosity is getting the best of me on why the initial iteration is slower than the rest.

For example, my output for code one with a longer arbitary input than what's shown above yields:

arbitrary string
That took 32 miliseconds to write.
arbitrary string
That took 51 miliseconds to write.
arbitrary string
That took 50 miliseconds to write.
arbitrary string
That took 50 miliseconds to write.
arbitrary string
That took 50 miliseconds to write.
arbitrary string
That took 50 miliseconds to write.
arbitrary string
That took 51 miliseconds to write.
arbitrary string
That took 50 miliseconds to write.
....

I'm assuming it has to do with something native to the Arduino IDE. Perhaps allocating memory or initializing built in packages or something. :o

At any rate, thanks in advance!

-C

First off, Serial.println() does not transmit everything over the serial port before it returns. It simply copies the data into an internal buffer and, using interrupts in the background, clocks out all the data. If you want to wait until everything has been sent, you need to use Serial.flush() [we all know, poor choice of names]

The difference you are seeing is most likely due to the String class and/or previous Serial.println() function calls since the buffer may be full.

I'd start by putting in the Serial.flush() before you figure out the final time. I would also invest some time into learning how to NOT use the String class since it dynamically allocates memory which is an extremely scare quantity on AVR Arduinos and will eventually bite you