I'm interested in running a program at a specific frequency (like 25MHz) on my 2GHz+ processor. The only method I can think of for doing something like this is using a microsecond precision sleep function, but I am unsure of how to calculate how long the thread should sleep for in order to match a specific frequency. Any tips or other ideas? I'm doing this in C on an X86 Linux OS.
There are a couple of problems here. This first what you are trying to simulate. Modern processors clock at 2Ghz but pipeline instructions so an individual instruction may take 10-30 clocks to finish. By putting a sleep in the thread you break the pipe-line. The second is how granular you want to have you simulation. Do you need to have instruction level timing of can we fake it by putting some space between functions.
My last thought is that you are likely not wanting to simulate a modern processor running at 25Mhz, but some type of ARM chip on an embedded device. If this is the case there are very good simulators for most of these chips already on the market. Compile your code to native instructions for your target chip, them use an already available simulator if one is available.
Edit:
So as I now understand it you want to execute an instruction on of a virtual processor 25M times a second. What I might try is an adaptive approach. You have lots of time to "mess around" between instructions. start by putting some spacing, sleep will probably work, between each instruction. Note in an array with as much precision as possible when each virtual clock started keep a rolling average of say the last 25, 100 or 1000 cycles. If the average rises above 25Mhz start adding more space. If it is too slow reduce the space.
As I said originally, it is very hard to calculate the amount of time an instruction takes on a modern processor. The first set of instructions may run a little too fast or slow, but a technique like this should keep it as close to the right speed as a typical oscillator on a comparable hardware implementation would.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With