Detecting the number of processors

后端 未结 8 1620
耶瑟儿~
耶瑟儿~ 2020-11-30 10:50

How do you detect the number of physical processors/cores in .net?

8条回答
  •  清歌不尽
    2020-11-30 11:35

    While Environment.ProcessorCount will indeed get you the number of virtual processors in the system, that may not be the number of processors available to your process. I whipped up a quick little static class/property to get exactly that:

    using System;
    using System.Diagnostics;
    
    /// 
    /// Provides a single property which gets the number of processor threads
    /// available to the currently executing process.
    /// 
    internal static class ProcessInfo
    {
        /// 
        /// Gets the number of processors.
        /// 
        /// The number of processors.
        internal static uint NumberOfProcessorThreads
        {
            get
            {
                uint processAffinityMask;
    
                using (var currentProcess = Process.GetCurrentProcess())
                {
                    processAffinityMask = (uint)currentProcess.ProcessorAffinity;
                }
    
                const uint BitsPerByte = 8;
                var loop = BitsPerByte * sizeof(uint);
                uint result = 0;
    
                while (--loop > 0)
                {
                    result += processAffinityMask & 1;
                    processAffinityMask >>= 1;
                }
    
                return (result == 0) ? 1 : result;
            }
        }
    }
    

提交回复
热议问题