My first naive attempt was to spawn 2 threads as a kernel - each thread with the highest priority, and then start a busy cycle in each thread and do some work. (More threads than cores, "steal" all the time that I can get from other threads in windows :-)
Using some kind of API to read the CPU load (maybe WMI or performance counters?), And then I will make each βyieldβ thread out of the busy cycle (sleep for a certain period of time for each cycle) until I get an approximate load in the cycle feedback.
This cycle will self-adjust: too high a load, more sleep. Too low load, less sleep. This is not an exact science, but I think that with some tuning you can get a stable load.
But I have no idea, really :-)
Happy coding.
Also, consider power management - sometimes it can block the CPU with a maximum value of%. Then fully load the CPU, and it will be maximum at this limit. (Windows 7, at least, has a built-in feature for this, depending on the processor and chip set - probably many third-party tools.)
The situation is becoming rather confused with new processors that dynamically synchronize depending on load and temperature, etc.
Here is my attempt at a βnaiveβ approach to .NET 3.5. Be sure to include the System.Management link.
Using the processor reported by the task manager is within a few percent of the target β the average value seems pretty black on my system. YMMV, but there is some flexibility in customization.
Happy coding (again).
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Management; using System.Threading; using System.Diagnostics; namespace CPULoad { class Program {
While Windows is a preventative operating system, code that runs in kernel mode β for example, drivers β is crowded out much less. Although this is not feasible in C # AFAIK, this should give a method of more stringent load adjustment than higher, but it also has a big cue ball of complexity (and the ability to break the whole system :-)
There is a Process.PriorityClass , but setting this to anything other than the usual one gave me consistent behavior.