# I don't understand this bug

I want to calculate the duration of a loop and use this value in my code. Hovewer the result (I called 'timeloop") gived me often 0 because the code is short, so I would like to constrain this value with minimum 1 with the code :
timeloop = max(millis() - timeprev , 1);

But in this example below, instead to have a Serial.print every second, I have the serial.print "timeloop = 1" every millisecond in the monitor like if the command 'mytimer += timeloop;' was broken.

Also if I add a delay(1) at the end, the code works correctly.
I tried also this formula without good result :
timeloop = max(millis() - long(timeprev),long(1));

The code :

``````unsigned long timeprev;
unsigned long timeloop;
int mytimer ;

void setup()
{
Serial.begin(9600);
}

void loop()
{
timeloop = max(millis() - timeprev , 1);
timeprev = millis();

if(mytimer > 1000)
{

Serial.print("timeloop = ");
Serial.println(timeloop);
Serial.println("--------------");

mytimer = 0;

}
else
{
mytimer += timeloop;
}

}
``````

Why not use micros()?

I don't need to be so accurate, also the main problem is that I don't understand why it dont work and it makes me mad.

Your loop() runs with very high speed. There is no limit for the speed. It runs faster than once per millisecond. That means that "mytimer += timeloop" is executated very often, and the 1000 is reached before you know it.

Why not measure it like everyone does:

``````unsigned long t1, t2, t;
t1 = micros();
....  // here the code to test
t2 = micros();
t = t2 - t1;
``````

"I want to calculate the duration of a loop"

I wouldn’t be surprised if your loop() runs in tens of microseconds.

Use Nick's profile timer:
http://www.gammon.com.au/forum/?id=11093

See ZIP file: http://www.gammon.com.au/Arduino/ProfileTimer.zip

If you look at the reference for the max(), it gives you this warning:

Because of the way the max() function is implemented, avoid using other functions inside the brackets, it may lead to incorrect results