Skip to content

Commit ce134ab

Browse files
committed
Sleep thread to account for tiered jit in Core runtimes 3.0 to 6.0.
1 parent 02f1381 commit ce134ab

File tree

1 file changed

+13
-1
lines changed

1 file changed

+13
-1
lines changed

src/BenchmarkDotNet/Engines/Engine.cs

+13-1
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@
33
using System.Globalization;
44
using System.Linq;
55
using System.Runtime.CompilerServices;
6+
using System.Threading;
67
using BenchmarkDotNet.Characteristics;
78
using BenchmarkDotNet.Jobs;
89
using BenchmarkDotNet.Portability;
@@ -214,15 +215,26 @@ private ClockSpan Measure(Action<long> action, long invokeCount)
214215

215216
private (GcStats, ThreadingStats, double) GetExtraStats(IterationData data)
216217
{
217-
// Warm up the GetAllocatedBytes function before starting the actual measurement.
218+
// Warm up the measurement functions before starting the actual measurement.
218219
DeadCodeEliminationHelper.KeepAliveWithoutBoxing(GcStats.ReadInitial());
220+
DeadCodeEliminationHelper.KeepAliveWithoutBoxing(GcStats.ReadFinal());
219221

220222
IterationSetupAction(); // we run iteration setup first, so even if it allocates, it is not included in the results
221223

222224
var initialThreadingStats = ThreadingStats.ReadInitial(); // this method might allocate
223225
var exceptionsStats = new ExceptionsStats(); // allocates
224226
exceptionsStats.StartListening(); // this method might allocate
225227

228+
if (RuntimeInformation.IsNetCore && Environment.Version.Major is >= 3 and <= 6 && Environment.GetEnvironmentVariable("COMPlus_TieredCompilation") != "0")
229+
{
230+
// #1542
231+
// We put the current thread to sleep so tiered jit can kick in, compile it's stuff
232+
// and NOT allocate anything on the background thread when we are measuring allocations.
233+
// This is only an issue on netcoreapp3.0 to net6.0. Tiered jit allocations were fixed in net7.0,
234+
// and netcoreapp2.X uses only GetAllocatedBytesForCurrentThread which doesn't capture the tiered jit allocations.
235+
Thread.Sleep(TimeSpan.FromMilliseconds(500));
236+
}
237+
226238
// GC collect before measuring allocations, as we do not collect during the measurement.
227239
ForceGcCollect();
228240
var gcStats = MeasureWithGc(data.InvokeCount / data.UnrollFactor);

0 commit comments

Comments
 (0)