Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to determine CPU cache size in .NET?

Tags:

c#

.net

windows

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 like to know how many elements of the matrices I could fit into cache to improve computational speed.

like image 769
GKalnytskyi Avatar asked Aug 09 '11 11:08

GKalnytskyi


2 Answers

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<uint> GetCacheSizes(CacheLevel level)
        {
            ManagementClass mc = new ManagementClass("Win32_CacheMemory");
            ManagementObjectCollection moc = mc.GetInstances();
            List<uint> cacheSizes = new List<uint>(moc.Count);

            cacheSizes.AddRange(moc
              .Cast<ManagementObject>()
              .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

like image 129
Tim Lloyd Avatar answered Oct 04 '22 09:10

Tim Lloyd


is this what you are looking for? The Win32_Processor class features L2CacheSize and L3CacheSize members.

like image 40
mtijn Avatar answered Oct 04 '22 09:10

mtijn