Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
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
6 changes: 5 additions & 1 deletion .gitattributes
Original file line number Diff line number Diff line change
@@ -1,2 +1,6 @@
# Auto detect text files and perform LF normalization
* text=auto
* text=auto

# cmd.exe may fail to find a label for goto / call in a batch file with LF line endings
*.bat text eol=crlf
*.ps1 text eol=crlf
236 changes: 236 additions & 0 deletions eng/get-pcore-affinity.ps1
Original file line number Diff line number Diff line change
@@ -0,0 +1,236 @@
<#
.SYNOPSIS
Prints the affinity mask that keeps only the performance cores.

.DESCRIPTION
Used by run-benchmarks.bat. On a hybrid CPU (Intel P/E cores, Snapdragon X,
Zen 5c) the scheduler may move a benchmark from a P core to an E core in the
middle of an iteration. That is not noise within StdDev but a several-fold
difference, and the mean of a whole run shifts with the share of time spent
on E cores. BenchmarkDotNet does not reject such a run; it only shows a
spread, and two runs of the same code disagree by 10-15%.

The cores come from GetLogicalProcessorInformationEx(RelationProcessorCore):
every physical core carries an EfficiencyClass. A higher class means a more
performant core, and the class is non-zero ONLY on hybrid machines. So:

* all cores of one class (a usual Xeon, Ryzen, any pre-hybrid Intel) -
nothing to restrict, the script prints nothing;
* several classes - the mask has every logical processor of the cores of
the highest class, SMT siblings included: the benchmarks are single
threaded, and an idle sibling does not disturb them.

A mask belongs to a processor group (KAFFINITY) and a process lives in one
group, so on machines with more than 64 logical processors only group 0 is
taken; if it has no P cores, the script prints nothing again.

Diagnostics go to stderr, in ASCII. stdout gets exactly one line with the
mask, or nothing; the caller must treat empty output as "no restriction",
not as an error.

.PARAMETER AsDecimal
Print the mask as a decimal number instead of hexadecimal (start /affinity
takes hexadecimal).

.OUTPUTS
System.String - the mask, or nothing.

.EXAMPLE
PS> .\get-pcore-affinity.ps1
3C03
#>
[CmdletBinding()]
param(
[switch] $AsDecimal
)

$ErrorActionPreference = 'Stop'
Set-StrictMode -Version Latest

function Write-Diagnostic([string] $message)
{
[Console]::Error.WriteLine($message)
}

# The buffer is read by offsets rather than through a [StructLayout] class:
# SYSTEM_LOGICAL_PROCESSOR_INFORMATION_EX has a variable length (GroupMask is an
# ANYSIZE_ARRAY), which the marshaller cannot express.
#
# SYSTEM_LOGICAL_PROCESSOR_INFORMATION_EX { DWORD Relationship; DWORD Size; union {...} }
# PROCESSOR_RELATIONSHIP { BYTE Flags; BYTE EfficiencyClass; BYTE Reserved[20];
# WORD GroupCount; GROUP_AFFINITY GroupMask[ANYSIZE_ARRAY]; }
# GROUP_AFFINITY { KAFFINITY Mask; WORD Group; WORD Reserved[3]; }
$source = @'
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Runtime.InteropServices;

namespace FastEnumBench
{
public struct CoreInfo
{
public byte EfficiencyClass;
public ushort Group;
public ulong Mask;
}

public static class TopologyProbe
{
private const int RelationProcessorCore = 0;

[DllImport("kernel32.dll", SetLastError = true)]
private static extern bool GetLogicalProcessorInformationEx(
int relationshipType, IntPtr buffer, ref int returnedLength);

public static CoreInfo[] GetCores()
{
int length = 0;
GetLogicalProcessorInformationEx(RelationProcessorCore, IntPtr.Zero, ref length);
if (length <= 0)
{
throw new Win32Exception(Marshal.GetLastWin32Error());
}

IntPtr buffer = Marshal.AllocHGlobal(length);
try
{
if (!GetLogicalProcessorInformationEx(RelationProcessorCore, buffer, ref length))
{
throw new Win32Exception(Marshal.GetLastWin32Error());
}

// GROUP_AFFINITY: ULONG_PTR + WORD + WORD[3], so 16 bytes on x64 and 12 on x86.
int groupAffinitySize = IntPtr.Size + 8;
var cores = new List<CoreInfo>();

int offset = 0;
while (offset + 8 <= length)
{
int relationship = Marshal.ReadInt32(buffer, offset);
int size = Marshal.ReadInt32(buffer, offset + 4);
if (size <= 0)
{
break;
}

if (relationship == RelationProcessorCore)
{
int processor = offset + 8;
byte efficiencyClass = Marshal.ReadByte(buffer, processor + 1);
int groupCount = (ushort)Marshal.ReadInt16(buffer, processor + 22);

for (int i = 0; i < groupCount; i++)
{
int groupAffinity = processor + 24 + (i * groupAffinitySize);
ulong mask = IntPtr.Size == 8
? (ulong)Marshal.ReadInt64(buffer, groupAffinity)
: (ulong)(uint)Marshal.ReadInt32(buffer, groupAffinity);

cores.Add(new CoreInfo
{
EfficiencyClass = efficiencyClass,
Group = (ushort)Marshal.ReadInt16(buffer, groupAffinity + IntPtr.Size),
Mask = mask
});
}
}

offset += size;
}

return cores.ToArray();
}
finally
{
Marshal.FreeHGlobal(buffer);
}
}
}
}
'@

function Get-BitCount([uint64] $mask)
{
$count = 0
while ($mask -ne 0)
{
$mask = $mask -band ($mask - 1)
$count++
}

return $count
}

try
{
if (-not ('FastEnumBench.TopologyProbe' -as [type]))
{
Add-Type -TypeDefinition $source -Language CSharp -ErrorAction Stop
}

$cores = @([FastEnumBench.TopologyProbe]::GetCores())
}
catch
{
Write-Diagnostic ("P-core detection failed: " + $_.Exception.Message)
Write-Diagnostic "Falling back to the default affinity (all cores)."
exit 0
}

if ($cores.Count -eq 0)
{
Write-Diagnostic "P-core detection: the OS reported no processor cores, using all cores."
exit 0
}

$classes = @($cores | ForEach-Object { [int] $_.EfficiencyClass } | Sort-Object -Unique)
if ($classes.Count -le 1)
{
Write-Diagnostic ("P-core detection: uniform CPU, all " + $cores.Count +
" cores share efficiency class " + $classes[0] + " - no affinity mask needed.")
exit 0
}

$topClass = $classes[-1]
$fast = @($cores | Where-Object { [int] $_.EfficiencyClass -eq $topClass -and $_.Group -eq 0 })
if ($fast.Count -eq 0)
{
Write-Diagnostic ("P-core detection: processor group 0 has no cores of the fastest class " +
$topClass + " - a mask would only narrow the run, using all cores.")
exit 0
}

$mask = [uint64] 0
foreach ($core in $fast)
{
$mask = $mask -bor $core.Mask
}

if ($mask -eq 0)
{
Write-Diagnostic "P-core detection: the fastest cores carry an empty affinity mask, using all cores."
exit 0
}

$groupZeroTotal = 0
foreach ($core in $cores)
{
if ($core.Group -eq 0)
{
$groupZeroTotal += Get-BitCount $core.Mask
}
}

Write-Diagnostic ("P-core detection: hybrid CPU, efficiency classes " + ($classes -join ',') +
"; " + $fast.Count + " core(s) of class " + $topClass + " -> " + (Get-BitCount $mask) +
" of " + $groupZeroTotal + " logical CPUs in group 0.")

if ($AsDecimal)
{
Write-Output ([string] $mask)
}
else
{
Write-Output ('{0:X}' -f $mask)
}
146 changes: 146 additions & 0 deletions run-benchmarks.bat
Original file line number Diff line number Diff line change
@@ -0,0 +1,146 @@
@echo off
rem ---------------------------------------------------------------------------
rem Runs the FastEnum benchmarks pinned to the performance cores and prints
rem the result tables only.
rem
rem Everything dotnet build and BenchmarkDotNet print - package restore, the
rem generated exe per job, per-iteration progress - goes to the log file. The
rem console gets only the markdown tables BenchmarkDotNet exports as
rem *-report-github.md.
rem
rem Arguments are passed to BenchmarkDotNet as they are; with none it runs
rem every benchmark (--filter *).
rem
rem run-benchmarks.bat - all benchmarks
rem run-benchmarks.bat --filter *NonConstantInput* - one class
rem
rem On a hybrid CPU the run is pinned to the performance cores - see the
rem affinity block below and eng\get-pcore-affinity.ps1.
rem
rem ASCII only on purpose: cmd.exe reads batch files in the OEM codepage, so
rem non-ASCII comments here would be mangled into unparsable commands.
rem ---------------------------------------------------------------------------

setlocal

cd /d "%~dp0"

set "PROJECT=src\insights\FastEnum.Benchmarks\FastEnum.Benchmarks.csproj"
set "HOSTEXE=src\artifacts\bin\FastEnum.Benchmarks\release_net11.0\FastEnum.Benchmarks.exe"
set "ARTIFACTS=%CD%\BenchmarkDotNet.Artifacts"
set "LOG=%CD%\benchmarks.log"

set "BENCHARGS=%*"
if not defined BENCHARGS set "BENCHARGS=--filter *"

rem Remembered now, restored after the reports are printed - see :restorecp.
rem Split on the colon only and trim afterwards: chcp's message is localized and
rem its wording contains spaces, so a space delimiter would pick up a word.
for /f "tokens=2 delims=:" %%C in ('chcp') do for /f "tokens=*" %%D in ("%%C") do set "OLDCP=%%D"

rem Report file names are derived from class names, so a stale report left by a
rem renamed benchmark would be printed below as if it came from this run.
if exist "%ARTIFACTS%" rd /s /q "%ARTIFACTS%"
if exist "%LOG%" del /q "%LOG%"

rem A hybrid CPU (Intel P/E cores, Snapdragon X, Zen 5c) lets the scheduler move
rem a benchmark from a P core to an E core in the middle of an iteration, and that
rem is a several-fold difference, not noise within StdDev - BenchmarkDotNet only
rem reports it as a spread, and two runs of the same code disagree by 10-15%.
rem eng\get-pcore-affinity.ps1 asks Windows for the efficiency class of every
rem physical core and prints the mask of the fastest ones; on a CPU whose cores
rem are all equal it prints nothing and the run stays unrestricted. Its own
rem diagnostics go to the log.
rem
rem Set FASTENUM_BENCH_AFFINITY to a hex mask to pin the run by hand, or to
rem "off" to run on every core.
set "AFFINITY="
if defined FASTENUM_BENCH_AFFINITY (
if /i not "%FASTENUM_BENCH_AFFINITY%"=="off" set "AFFINITY=%FASTENUM_BENCH_AFFINITY%"
) else (
for /f "usebackq tokens=1" %%M in (`powershell -NoLogo -NoProfile -ExecutionPolicy Bypass -File "%~dp0eng\get-pcore-affinity.ps1" 2^>^>"%LOG%"`) do set "AFFINITY=%%M"
)

rem Whatever powershell.exe writes to stdout ends up here, and that is not always
rem the mask: a missing script file, for one, makes it print its logo instead. A
rem non-mask would be handed to start below, which would refuse to launch anything.
if defined AFFINITY call :checkmask

if defined AFFINITY (
echo Affinity: 0x%AFFINITY% - the run is pinned to these CPUs.
) else (
echo Affinity: not restricted.
)

echo [1/2] Building Release: %PROJECT% ...
dotnet build -c Release -f net11.0 "%PROJECT%" --nologo -v quiet >> "%LOG%" 2>&1
if errorlevel 1 goto :failed

rem The mask goes onto the host process rather than into BenchmarkDotNet's own
rem --affinity, for two reasons. Windows hands a process affinity down to every
rem child it starts, so the one mask covers the per-job exe BenchmarkDotNet
rem generates, builds and runs - and it is in place BEFORE the runtime of those
rem children starts, so the GC sizes its heaps for the cores they will actually
rem get. --affinity is applied to an already running process and is parsed as a
rem signed 32-bit number, so it cannot even express cores above CPU 30.
rem
rem Priority goes on for the same reason and by the same mechanism. Above normal
rem rather than high on purpose - high starves the shell that has to collect the
rem output, and the point is to lose fewer timeslices to background work.
rem
rem /b keeps the child in this console, so the redirection below still reaches it,
rem and /wait is what makes errorlevel below mean the benchmark run.
if defined AFFINITY (
echo [2/2] Running benchmarks on the performance cores, above normal priority ...
start "FastEnum benchmarks" /affinity %AFFINITY% /abovenormal /b /wait "%HOSTEXE%" %BENCHARGS% >> "%LOG%" 2>&1
) else (
echo [2/2] Running benchmarks, above normal priority ...
start "FastEnum benchmarks" /abovenormal /b /wait "%HOSTEXE%" %BENCHARGS% >> "%LOG%" 2>&1
)
if errorlevel 1 goto :failed

if not exist "%ARTIFACTS%\results\*-report-github.md" goto :noresults

rem Not "type": the reports are UTF-8 and contain the micro sign, which the OEM
rem codepage turns into mojibake. They are also HTML-escaped by BenchmarkDotNet's
rem github exporter. PowerShell reads them as UTF-8 and unescapes; chcp makes the
rem console show it.
chcp 65001 > nul
powershell -NoProfile -Command "[Console]::OutputEncoding = [Text.Encoding]::UTF8; Get-ChildItem '%ARTIFACTS%\results' -Filter '*-report-github.md' | ForEach-Object { Write-Output ''; Write-Output ('=' * 79); Write-Output (' ' + $_.BaseName); Write-Output ('=' * 79); Write-Output ([System.Net.WebUtility]::HtmlDecode((Get-Content -Raw -Encoding UTF8 $_.FullName))) }"
call :restorecp

echo Full log: %LOG%
endlocal
exit /b 0

rem The console codepage is process-wide and survives this script, so put back
rem whatever the user had before.
:restorecp
if defined OLDCP chcp %OLDCP% > nul
goto :eof

rem No space before the pipe: it would be echoed as part of the mask.
:checkmask
if /i "%AFFINITY:~0,2%"=="0x" set "AFFINITY=%AFFINITY:~2%"
echo %AFFINITY%| findstr /r /i /c:"^[0-9a-f][0-9a-f]*$" > nul
if errorlevel 1 (
echo Affinity: "%AFFINITY%" is not a hex mask, ignoring it.
set "AFFINITY="
)
goto :eof

:noresults
echo.
echo No report files were produced. Full log: %LOG%
endlocal
exit /b 1

:failed
echo.
echo BUILD OR RUN FAILED. Log tail:
echo -------------------------------------------------------------------------------
powershell -NoProfile -Command "Get-Content -Tail 40 '%LOG%'"
echo -------------------------------------------------------------------------------
echo Full log: %LOG%
endlocal
exit /b 1
Loading