Is there a way to make a function take an exact number of clock cycles?
To the best of my knowledge, there is not. What you speak of is possible, but it must be done manually by counting cycles, and I suspect it wouldn't actually help you. (And then you get into CISC issues where instructions can take different amounts of time to execute, potentially depending on arguments. Arduino (the actual one) is kinda safe from that, but branch instructions still take multiple cycles, for instance. This says nothing about all the boards that work with, but aren't, Arduinos.)

There are two potential routes for this.


If this is for crypto, where you want to avoid side-channel attacks by detecting the length of an authentication or hashing function, it's not a good idea. Use a well-known library to do it instead, since in practicality it's not a good or safe idea to write your own (although if it's for a homemade door lock or safe lock, it's probably not a relevant issue since there are larger and more important security issues that will likely be found first despite your best efforts).
If, as I suspect, you simply want a piece of code to run at very precise time intervals, I suggest you look up something like the FreeRTOS port for Arduino. That will let you schedule a task to run preemptively so that it will always run at intervals. The BWOD sketch is still quite accurate, mind you, and below is a self-correcting version that compensates for any times that it might run a bit late (meaning that it should ALWAYS execute with millisecond precision, repeatably):


  unsigned long currentMillis = millis();//and you could always use micros()

  if (currentMillis - previousMillis &gt;= interval) {
    // save the last time you blinked the LED
    previousMillis += interval;//adjustment for additional accuracy

    //The task you want to run would go below:
    // if the LED is off turn it on and vice-versa:
    if (ledState == LOW) {
      ledState = HIGH;
    } else {
      ledState = LOW;
    }

    // set the LED with the ledState of the variable:
    digitalWrite(ledPin, ledState);
  }


The caveat to your stated goal is that any microprocessor WILL NOT execute code exactly when you want. Arduino too is incapable of this, since even a blank sketch runs several interrupts that will take over the processor for short periods of time, causing your hypothetical sketch to be delayed. You HAVE to use a reference method like BWOD or a scheduler like FreeRTOS. These use a reference or set up their own interrupt to make sure that they run on time, with the only interrupts that could be an issue being the ones that run during that instance of the task.

What this means is that they have a bit of overhead to add spacing between tasks so that if one is delayed, it won't cause the next to run late. So do mind that you'll lose a quite small percentage of CPU time to your scheduler, but if that's really an issue, find a better board (like TI TIVA/Energia IDE).