How can I get a count of “Available” processors for my application?

六月ゝ 毕业季﹏ 提交于 2019-12-22 09:33:54

问题


I know how to get the number of physical, and number of logical processors on my machine, but I want to know how many logical processors my application has access to.

For instance, I develop on a quad core machine, but I have a number of single core users out there, and in many instances I "dumb down" the interface, or run into locking problems that a multi-core system never experiences.

So, to that end I have set up VSTS to build my app in either debug or "Debug Single Core". The goal there is basically to set the processor affinity to core "0", which by looking at the windows task manager is working as expected.

My problem is, I just noticed, ( and hind sight says it should have been obvious ), that throughout my code I have Environment.ProcessorCount >= something, which works great for truly single core machines, but doesn't give me a read on my single "logically available core".

How can I get the number of "available" logical cores?

C# preferred


回答1:


A special thanks goes out to Jesse Slicer's answer found here.

Although not the accepted answer to the question asked, it IS the answer I am looking for.

Here is basicly what I ended up with based on Jesse's answer.

#if !DEBUG
                return Environment.ProcessorCount;
#endif
                using (Process currentProcess = Process.GetCurrentProcess())
                {
                    var processAffinityMask =
                        (uint) currentProcess.ProcessorAffinity;
                    const uint BitsPerByte = 8;
                    var loop = BitsPerByte*sizeof (uint);
                    uint result = 0;

                    while (loop > 0)
                    {
                        --loop;
                        result += (processAffinityMask & 1);
                        processAffinityMask >>= 1;
                    }

                    return Convert.ToInt32((result != 0) ? result : 1);
                }


来源:https://stackoverflow.com/questions/2134566/how-can-i-get-a-count-of-available-processors-for-my-application

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!