Skip to content
Open
Show file tree
Hide file tree
Changes from 2 commits
Commits
Show all changes
15 commits
Select commit Hold shift + click to select a range
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
166 changes: 161 additions & 5 deletions src/BenchmarkDotNet/Environments/PhysicalMemoryInfo.cs
Original file line number Diff line number Diff line change
@@ -1,7 +1,11 @@
using BenchmarkDotNet.Detectors;
using BenchmarkDotNet.Extensions;
using System;
using System.Diagnostics;
using System.IO;
using System.Runtime.InteropServices;
using System.Runtime.Versioning;
using System.Text;
using System.Text.RegularExpressions;
using Windows.Win32;
using Windows.Win32.System.SystemInformation;
Expand All @@ -12,24 +16,44 @@ public class PhysicalMemoryInfo
{
public long TotalPhysicalBytes { get; }
public long? AvailablePhysicalBytes { get; }
public long? FrequencyMHz { get; }
public string? MemoryType { get; }

public PhysicalMemoryInfo(long totalPhysicalBytes, long? availablePhysicalBytes = null)
public PhysicalMemoryInfo(long totalPhysicalBytes, long? availablePhysicalBytes = null, long? frequencyMHz = null, string? memoryType = null)
{
TotalPhysicalBytes = totalPhysicalBytes;
AvailablePhysicalBytes = availablePhysicalBytes;
FrequencyMHz = frequencyMHz;
MemoryType = memoryType;
}

public string ToFormattedString()
{
double totalGb = TotalPhysicalBytes / (1024.0 * 1024.0 * 1024.0);
var sb = new StringBuilder();
sb.Append($"{Math.Round(totalGb, 2)} GB");
Comment thread
timcassell marked this conversation as resolved.
Outdated

if (MemoryType.IsNotBlank() || FrequencyMHz.HasValue)
{
sb.Append(" (");
if (MemoryType.IsNotBlank())
sb.Append(MemoryType);
if (FrequencyMHz.HasValue)
{
if (MemoryType.IsNotBlank())
sb.Append('-');
sb.Append($"{FrequencyMHz}MHz");
Comment thread
timcassell marked this conversation as resolved.
Outdated
}
sb.Append(')');
}

if (AvailablePhysicalBytes.HasValue)
{
double availableGb = AvailablePhysicalBytes.Value / (1024.0 * 1024.0 * 1024.0);
return $"{Math.Round(totalGb, 2)} GB Total, {Math.Round(availableGb, 2)} GB Available";
sb.Append($", {Math.Round(availableGb, 2)} GB Available");
Comment thread
timcassell marked this conversation as resolved.
}

return $"{Math.Round(totalGb, 2)} GB";
return sb.ToString();
}
}

Expand Down Expand Up @@ -61,7 +85,10 @@ public static class SystemMemory
{
var memStatus = new MEMORYSTATUSEX { dwLength = (uint)Marshal.SizeOf<MEMORYSTATUSEX>() };
if (PInvoke.GlobalMemoryStatusEx(ref memStatus))
return new PhysicalMemoryInfo((long)memStatus.ullTotalPhys, (long)memStatus.ullAvailPhys);
{
var (freq, type) = GetLinuxOrWindowsMemoryDetails();
return new PhysicalMemoryInfo((long)memStatus.ullTotalPhys, (long)memStatus.ullAvailPhys, freq, type);
}

return null;
}
Expand Down Expand Up @@ -91,11 +118,140 @@ public static class SystemMemory
}

if (total > 0)
return new PhysicalMemoryInfo(total, available);
{
var (freq, type) = GetLinuxOrWindowsMemoryDetails();
return new PhysicalMemoryInfo(total, available, freq, type);
}
}
return null;
}

private static (long? FrequencyMHz, string? MemoryType) GetLinuxOrWindowsMemoryDetails()
Comment thread
timcassell marked this conversation as resolved.
Outdated

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It looks like this should be 2 separate methods.

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Please address

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

You did not address. GetLinuxOrWindowsMemoryDetails should be split to GetLinuxMemoryDetails and GetWindowsMemoryDetails.

{
try
{
if (OsDetector.IsWindows7OrLater())
{
return GetWindowsSmbiosMemoryDetails();
}

// Try reading /sys/devices/system/edac/mc/ on Linux
if (Directory.Exists("/sys/devices/system/edac/mc"))
{
foreach (var mcDir in Directory.GetDirectories("/sys/devices/system/edac/mc", "mc*"))
{
foreach (var dimmDir in Directory.GetDirectories(mcDir, "dimm*"))
{
string typePath = Path.Combine(dimmDir, "dimm_mem_type");
if (File.Exists(typePath))
{
string memType = File.ReadAllText(typePath).Trim();
if (!string.IsNullOrEmpty(memType) && memType != "Unspecified")
Comment thread
timcassell marked this conversation as resolved.
Outdated
return (null, memType);
}
}
}
}
}
catch
{
// Ignore fallback failures
}

return (null, null);
}

[SupportedOSPlatform("windows5.1.2600")]
private static (long? FrequencyMHz, string? MemoryType) GetWindowsSmbiosMemoryDetails()
{
try
{
const uint rsMb = 0x52534D42; // 'RSMB'
uint bufferSize = NativeMethods.GetSystemFirmwareTable(rsMb, 0, IntPtr.Zero, 0);
if (bufferSize == 0)
return (null, null);

byte[] buffer = new byte[bufferSize];
if (NativeMethods.GetSystemFirmwareTable(rsMb, 0, buffer, bufferSize) == 0)
return (null, null);

// SMBIOS table header: Data at offset 8
int offset = 8;
long? maxSpeed = null;
string? detectedType = null;

while (offset + 4 <= buffer.Length)
{
byte type = buffer[offset];
byte length = buffer[offset + 1];

if (length < 4 || offset + length > buffer.Length)
break;

// Type 17: Memory Device
if (type == 17 && length >= 0x15)
{
// Memory Type at offset 0x12
byte rawMemoryType = buffer[offset + 0x12];
string? memTypeStr = MapSmbiosMemoryType(rawMemoryType);
if (memTypeStr != null && detectedType == null)
{
detectedType = memTypeStr;
}

// Speed in MHz at offset 0x15 (WORD)
if (length >= 0x17)
{
ushort speed = (ushort)(buffer[offset + 0x15] | (buffer[offset + 0x16] << 8));
if (speed > 0 && speed < 0xFFFF)
{
if (maxSpeed == null || speed > maxSpeed.Value)
{
maxSpeed = speed;
}
}
}
}

// Move past formatted area
offset += length;

// Skip unformatted string section (double null-terminated)
while (offset < buffer.Length - 1 && !(buffer[offset] == 0 && buffer[offset + 1] == 0))
{
offset++;
}
offset += 2;
}

return (maxSpeed, detectedType);
}
catch
{
return (null, null);
}
}

private static class NativeMethods
Comment thread
timcassell marked this conversation as resolved.
Outdated
{
[DllImport("kernel32.dll", SetLastError = true)]
public static extern uint GetSystemFirmwareTable(uint firmwareTableProviderSignature, uint firmwareTableID, byte[] pFirmwareTableBuffer, uint bufferSize);

[DllImport("kernel32.dll", SetLastError = true)]
public static extern uint GetSystemFirmwareTable(uint firmwareTableProviderSignature, uint firmwareTableID, IntPtr pFirmwareTableBuffer, uint bufferSize);
}

private static string? MapSmbiosMemoryType(byte type) => type switch
{
0x1A => "DDR3",
0x1A + 1 => "DDR4",
Comment thread
timcassell marked this conversation as resolved.
Outdated
0x1A + 2 => "LPDDR3",
0x1A + 3 => "LPDDR4",
0x22 => "DDR5",
0x23 => "LPDDR5",
_ => null
};

private static PhysicalMemoryInfo? GetMacMemory()
{
long total = 0;
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
using BenchmarkDotNet.Environments;
using Xunit;

namespace BenchmarkDotNet.Tests.Environments
{
public class PhysicalMemoryInfoTests
{
[Fact]
public void PhysicalMemoryInfo_ParsesAndConstructsCorrectly()
{
var memInfo = new PhysicalMemoryInfo(16000000000, null, 3200, "DDR4");
Assert.Equal(16000000000L, memInfo.TotalPhysicalBytes);
Assert.Equal(3200L, memInfo.FrequencyMHz);
Assert.Equal("DDR4", memInfo.MemoryType);
}
}
}