Question

I was wondering if there was a possibility to let a thread sleep for a certain amount of CPU-cycles?

I thought about just inserting "nop"'s but I'm not sure if they get optimized away and I was hoping for a high-level solution.

Is there anything nice you could recommend me? If not can I prevent, that manually inserted "nop"'s get optimized away without disabling all optimizations? Kind regards

Lukas Häfliger

EDIT: as another question: is it possible to measure the amount of cycles needed during execution for a certain code fragment?

Was it helpful?

Solution

In short, no, because there isn't a 1:1 mapping between cycles and instructions (indeed, many instructions are executed per-cycle), and when you have things like instruction-pipelining, branch-prediction and speculative-execution it clearly becomes unpredictable.

Another reason is that there isn't an interrupt based on CPU cycles (or instructions), instead threads sleep based on a hardware timer interrupt or the operating system scheduler polling the current thread queue given the current time.

Finally, even if it were possible in hardware, the Windows API (which .NET uses internally) does not expose any other sleeping parameters besides a timespan in miliseconds (and a milisecond is potentially tens of thousands of CPU cycles anyway).

In C# the question is rather nonsensical because the code will be JIT-compiled based on the current platform, which means you can't predict the hardware instructions used for a given block of code, and even then there is the possibility that your CIL might be executed by an interpreter instead of JIT'd to reduce startup latency, and that throws the CPU instruction count waaaay off.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top