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.
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
is this what you are looking for? The Win32_Processor class features L2CacheSize and L3CacheSize members.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With