how to determine CPU cache size in .NET?

后端 未结 4 1037
谎友^
谎友^ 2021-01-13 10:32

I would like to know if there is a way to determine CPU cache size in managed code?

I am writing a Strassen\'s algorithm for matrix multiplication in C# and would li

4条回答
  •  爱一瞬间的悲伤
    2021-01-13 11:19

    You can use WMI to retrieve cache information.

    You will first need to add a reference to System.Management.dll to your project, then you can use the following code:

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Management;
    
    namespace Scratch
    {
        public enum CacheLevel : ushort 
        {
            Level1 = 3,
            Level2 = 4,
            Level3 = 5,
        }
    
        public static class CPUInfo
        {
            public static List GetCacheSizes(CacheLevel level)
            {
                ManagementClass mc = new ManagementClass("Win32_CacheMemory");
                ManagementObjectCollection moc = mc.GetInstances();
                List cacheSizes = new List(moc.Count);
    
                cacheSizes.AddRange(moc
                  .Cast()
                  .Where(p => (ushort)(p.Properties["Level"].Value) == (ushort)level)
                  .Select(p => (uint)(p.Properties["MaxCacheSize"].Value)));
    
                return cacheSizes;
            }
        }
    }
    

    Full details of the Win32_CacheMemory WMI class is available at:

    http://msdn.microsoft.com/en-us/library/aa394080(v=vs.85).aspx

提交回复
热议问题