I'm trying to fully understand what a clock cycle is, so I've come up with a test example that I'd like someone to confirm or dispel and offer a better understanding to. If I have this simple line of code, a while loop, running on a device
while(true)
{
int x = 5;
}
Does the command: int x = 5 get executed once per clock cycle? In other words, is the clock speed the speed at which the device is able to read and execute commands per unit of time measure?
Where do I begin...
Any processor has a "clock" that ensures that bits of electronics have time to transition from one state to another before the next thing happens. At the speeds of modern devices, nothing is "instantaneous" - a "step" becomes a "slope", and even a very short trace will cause delays in tranmission of electical signals.
Depending on the architecture of a CPU, it can do certain operations "in one clock cycle", while others take "multiple cycles". Think of long division - you do a series of subtract - shift operations, and you don't know what you need to do next until you have completed the previous part of the operation. For addition, it is easier to see how you could achieve a complete operation in one cycle.
When a particular "high level" instruction is translated into machine code, the resulting code can take one or more cycles - and a simple instruction can take one or more steps. Depending on the compiler, the target, and the optimizations chosen, any of the following could happen in your above code:
the compiler realizes that the "while" condition is always true, and that nothing changes inside the loop. It further realizes that you never use the value of x, and it chooses not to implement the instruction at all
the compiler decides to use a built in register for the int
variable x
, and it initializes it at compile time. No time taken during the execution of the loop
the compiler loads '5' into a register, looks up the offset of x in a table, computes a pointer, and copies the register into the offset address. Could be any number of cycles.
Not sure this really helped you - but the question is rather complicated...