I am writing a rather resource-intensive application, and I am trying to find a way to let the user of said app decide what resources, exactly the app should use.
Part of the problem here is knowing what the CPUs are capable of -> I imagine that if the user wants the app to use 5 cores on a AMD Phenom II X6, I can get away with throwing everything at those 5 cores. On the other hand, if the processor is an Intel i7 or an AMD FX-8510, some of those cores share various components. What then should I do, to ensure I don’t schedule something accidentally to the hyper-threader scheduler, or something to that extent?
I am trying to avoid the scenario where a CPU chokes because I am throwing everything at the wrong part of it (was an old problem). Any ideas?
Thread scheduler in operating system has all information necessary (number of physical CPU cores, which logical cores shares resources, which cores are parked to safe energy, if hyperthreading is enabled, which cores uses turbo frequency, what resources are used by another programs, etc…) for efficient CPU resource allocation. You program has no knowledge about these things, so best thing you can do is to let OS decide how to allocate resources. Even without any special support in your program, user can limit resources used by program by setting process priority or processor affinity if he wants.
One thing you can try is to create number of threads according with number of CPU cores (returned by Environment.ProcessorCount). If you thing that scheduling one thread per physical core (instead of one thread per logical core) will perform better, you can play with Process.GetCurrentProcess().ProcessorAffinity property – set it to 0x55555555 on CPUs with hyperthreading, but this can also make things worse than before (what if some future CPU will have 3 logical cores per physical core instead of 2, or what if another program set processor affinity to the same cores?).