Skip to content

[Bug Fix] High Performance Plan Fix #2485

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Draft
wants to merge 4 commits into
base: master
Choose a base branch
from
Draft
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
34 changes: 32 additions & 2 deletions src/BenchmarkDotNet/Helpers/PowerManagementHelper.cs
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Runtime.InteropServices;
using System.Text;
Expand Down Expand Up @@ -50,7 +51,7 @@ internal static string CurrentPlanFriendlyName

internal static bool Set(Guid newPolicy)
{
return PowerSetActiveScheme(IntPtr.Zero, ref newPolicy) == 0;
return PowerSetActiveScheme(IntPtr.Zero, ref newPolicy) == 0;
}

[DllImport("powrprof.dll", CharSet = CharSet.Unicode, ExactSpelling = true)]
Expand All @@ -61,5 +62,34 @@ internal static bool Set(Guid newPolicy)

[DllImport("powrprof.dll", ExactSpelling = true)]
private static extern uint PowerGetActiveScheme(IntPtr UserRootPowerKey, ref IntPtr ActivePolicyGuid);

[DllImport("powrprof.dll", SetLastError = true)]
private static extern uint PowerEnumerate(IntPtr RootPowerKey, IntPtr SchemeGuid, IntPtr SubGroupOfPowerSettingsGuid, uint AccessFlags, uint Index, ref Guid Buffer, ref uint BufferSize);

internal static IEnumerable<Guid> EnumerateAllPlanGuids()
{
const uint ACCESS_SCHEME = 16;
uint index = 0;
while (true)
{
Guid schemeGuid = Guid.Empty;
uint size = (uint)Marshal.SizeOf(typeof(Guid));
uint res = PowerEnumerate(IntPtr.Zero, IntPtr.Zero, IntPtr.Zero, ACCESS_SCHEME, index, ref schemeGuid, ref size);
if (res != 0)
break;
yield return schemeGuid;
index++;
}
}

internal static bool PlanExists(Guid planGuid)
{
foreach (var guid in EnumerateAllPlanGuids())
{
if (guid == planGuid)
return true;
}
return false;
}
}
}
}
20 changes: 18 additions & 2 deletions src/BenchmarkDotNet/Running/BenchmarkRunnerClean.cs
Original file line number Diff line number Diff line change
Expand Up @@ -232,8 +232,24 @@ private static Summary Run(BenchmarkRunInfo benchmarkRunInfo,
{
var benchmark = benchmarks[i];

powerManagementApplier.ApplyPerformancePlan(benchmark.Job.Environment.PowerPlanMode
?? benchmark.Job.ResolveValue(EnvironmentMode.PowerPlanModeCharacteristic, EnvironmentResolver.Instance).GetValueOrDefault());
bool userExplicitlySetPlan = benchmark.Job.HasValue(EnvironmentMode.PowerPlanModeCharacteristic);

var requestedPlan = benchmark.Job.Environment.PowerPlanMode
?? benchmark.Job.ResolveValue(EnvironmentMode.PowerPlanModeCharacteristic, EnvironmentResolver.Instance).GetValueOrDefault();

// If the plan is not explicitly set and would downgrade Ultimate, skip changing
if (!userExplicitlySetPlan && requestedPlan == PowerManagementApplier.Map(PowerPlan.HighPerformance))
{
var ultimateGuid = PowerManagementApplier.Map(PowerPlan.UltimatePerformance);
var currentPlan = PowerManagementHelper.CurrentPlan;
if (currentPlan.HasValue && currentPlan.Value == ultimateGuid)
{
logger.WriteLineInfo("Already on Ultimate Performance; not switching to High Performance since no plan explicitly set in Job.");
continue;
Copy link
Collaborator

@timcassell timcassell Jul 24, 2025

Choose a reason for hiding this comment

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

This doesn't work, you're skipping the entire benchmark here. You should rather invert the branches, or move it to another function.

}
}

powerManagementApplier.ApplyPerformancePlan(requestedPlan);

var info = buildResults[benchmark];
var buildResult = info.buildResult;
Expand Down
18 changes: 17 additions & 1 deletion src/BenchmarkDotNet/Running/PowerManagementApplier.cs
Original file line number Diff line number Diff line change
Expand Up @@ -76,19 +76,35 @@ private void ApplyPlanByGuid(Guid guid)
isInitialized = true;
}

Guid currentActivePlan = (Guid)PowerManagementHelper.CurrentPlan;
Guid ultimatePerformanceGuid = PowerPlansDict[PowerPlan.UltimatePerformance];
Guid highPerformanceGuid = PowerPlansDict[PowerPlan.HighPerformance];

if (currentActivePlan == ultimatePerformanceGuid && guid == highPerformanceGuid)
{
if (!PowerManagementHelper.PlanExists(highPerformanceGuid))
{
logger.WriteLineInfo("Cannot setup High Performance power plan - plan doesn't exist on this system.");
return;
}
logger.WriteLineInfo("Changing from Ultimate Performance to explicitly configured High Performance plan.");
}

if (PowerManagementHelper.Set(guid))
{
powerPlanChanged = true;
var powerPlanFriendlyName = PowerManagementHelper.CurrentPlanFriendlyName;
logger.WriteLineInfo($"Setup power plan (GUID: {guid} FriendlyName: {powerPlanFriendlyName})");
}
else
{
logger.WriteLineError($"Cannot setup power plan (GUID: {guid})");
}
}
catch (Exception ex)
{
logger.WriteLineError($"Cannot setup power plan (GUID: {guid}, error message: {ex.Message})");
}
}
}
}
}
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
using BenchmarkDotNet.Environments;
using BenchmarkDotNet.Configs;
using BenchmarkDotNet.Environments;
using BenchmarkDotNet.Helpers;
using BenchmarkDotNet.Jobs;
using BenchmarkDotNet.Running;
using BenchmarkDotNet.Tests.Loggers;
using BenchmarkDotNet.Tests.XUnit;
Expand Down Expand Up @@ -42,5 +44,38 @@ public void TestPowerPlanShouldNotChange()

Assert.Equal(userPlan, PowerManagementHelper.CurrentPlan);
}

[FactEnvSpecific("Should keep power plan at Ultimate Performance if current power plan is Ultimate when a power plan is not specifically set", EnvRequirement.WindowsOnly)]
public void TestKeepingUltimatePowerPlan()
{
var ultimateGuid = PowerManagementApplier.Map(PowerPlan.UltimatePerformance);
var userPlan = PowerManagementHelper.CurrentPlan;

if (!PowerManagementHelper.PlanExists(ultimateGuid))
{
Output.WriteLine("Ultimate Performance plan does not exist or cannot be activated. Skipping test.");
return;
}

PowerManagementHelper.Set(ultimateGuid);

var job = Job.Default;

var config = ManualConfig.CreateEmpty().AddJob(job);

BenchmarkRunner.Run<DummyBenchmark>(config);

Assert.Equal(ultimateGuid.ToString(), PowerManagementHelper.CurrentPlan.ToString());

PowerManagementHelper.Set(userPlan.Value);
}

public class DummyBenchmark
{
[BenchmarkDotNet.Attributes.Benchmark]
public void DoNothing()
{
}
}
}
}
}
Loading