cost of Millis()

Hi,

I develop my first Arduino project which is my first embed project.
Usually I write higher code (like Java) and calling Time functions is very painful.

On this board, can I call Millis() in real time?

I.E.

void loop()
{
  ...
  if (millis()>x) {
     ...
  } 
  ...
  if (millis()>y) {
     ...
  } 
  ...
  if (millis()>z) {
     ...
  } 
}

Or should I write this:

void loop()
{
  unsigned long time = millis();
  ...
  if (time>x) {
     ...
  } 
  ...
  if (time>y) {
     ...
  } 
  ...
  if (time>z) {
     ...
  } 
}

thx

Either of your examples will run fine.

The only difference is in the first example, it is possible that the value of millis() can change between each if statement. With the second example, all of your if statements will be testing against the same value.

Whether that difference is important or not would depend on what exactly you are looking for.

Cheers!

Ok, but if reading the value of a variable costs 1 CPU cycle, 4 bytes for the value and 2 bytes for the address of the value. (?)
Calling Millis() costs only 1 CPU cycle and 4 bytes for the value? (I would like to compare the value and/or to apply bitmasks)

Calling Millis() costs only 1 CPU cycle and 4 bytes for the value?

Four bytes for the value, yes, but more than a single cycle for the CPU.
Still not likely to be as expensive as Java though.

(I would like to compare the value and/or to apply bitmasks)

Apply bitmasks to what?

While it is always good to consider efficiency and optimizations, you are early in the process. The time it takes to call millis() is very likely to be on of your last concerns.

The larger concern was already mentioned. Do you want the if-statements to evaluate against the same timestamp or not?

It is for my main loop.

I.E.

boolean step;
const uint8_t byteTime = 12; // bitRead(millis(), 12) =~ 4s

void loop()
{
  unsigned long time = millis();
  if (step != bitRead(time, byteTime)) {
    // it's time to do something
    if (step) {
      // read outdoor temperature
    } else {
      // read indoor temperature
    }
    step = bitRead(time, byteTime);
  }
}

Then an optimization could storing time as uint8_t after a bit rolling according to the targeting velocity :wink:

The bitRead() function expects an int as the first argument, not an unsigned long.

PaulS:
The bitRead() function expects an int as the first argument, not an unsigned long.

It does? Then why isn't that stated on the reference page.

Does this code only work with int?

Arduino.h:#define bitRead(value, bit) (((value) >> (bit)) & 0x01)

It does?

Not often I get two mistakes in one post. No, it doesn't. First I was thinking byte when I typed int. Second, the "function" is a macro, with no defined type. So, it can take any argument - byte, int, long, float, pointer, etc. Of course, not all make sense.