What is the easiest way to run some code each millisecond for a certain amount of time?

do this:

uint32_t currTime = millis();
constexpr uint32_t timeDiff = 120000;
while((millis() - currTime) < timeDIff){
//do stuff
}

However I do not know why you want to do a operation for "as much as possible" over a specific period of time. that could be millions of executions and the core may run hot. Unless you are trying to benchmark different mcus (by comparing the amount of instructions they can do in 2 min).

Many tasks take less than 1ms to run. For example, the 32U4 have a "two clock multiplier" that can do multiplications in two clock cycles. digitalWrite probably take a dozen nanoseconds.


If you want a framerate control (e.g. displaying some graphics on a screen), do this:

unsigned long lastFrameStart;
unsigned long nextFrameStart;
bool justRendered;
uint8_t lastFrameDurationMs;
uint16_t frameCount;
uint16_t frameDiff;


bool setFrameDiff
(uint16_t rate)
{
  frameDiff = rate;
  return 0;
}
bool nextFrame
(void)
{
  unsigned long now = millis();
  bool tooSoonForNextFrame = now < nextFrameStart;

  if (justRendered) {
    lastFrameDurationMs = now - lastFrameStart;
    justRendered = false;
    return false;
  }
  else if (tooSoonForNextFrame) {
    if ((uint8_t)(nextFrameStart - now) > 1)
      sleep(1);//delay(1) when the processor does not support "sleep" function
    return false;
  }

  // pre-render
  justRendered = true;
  lastFrameStart = now;
  nextFrameStart = now + frameDiff;
  frameCount++;
  //if (frameCount > 20000)
    //frameCount = frameCount - 20000;
  return true;
}

which also tell you the amout of frames that have passed.