This repository has been archived by the owner on Jul 15, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 55
/
BenchmarkTestInvoker.cs
327 lines (287 loc) · 13.6 KB
/
BenchmarkTestInvoker.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
using MathNet.Numerics.Statistics;
using Microsoft.Xunit.Performance.Analysis;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Reflection;
using System.Threading;
using System.Threading.Tasks;
using Xunit.Abstractions;
using Xunit.Sdk;
namespace Microsoft.Xunit.Performance
{
internal class BenchmarkTestInvoker : XunitTestInvoker
{
static bool _initialized;
static bool _loggingFailed;
static string _runId;
static IDisposable _etwLogger; // just to keep the logger rooted, so it doesn't get finalized during the run
public BenchmarkTestInvoker(ITest test,
IMessageBus messageBus,
Type testClass,
object[] constructorArguments,
MethodInfo testMethod,
object[] testMethodArguments,
IReadOnlyList<BeforeAfterTestAttribute> beforeAfterAttributes,
ExceptionAggregator aggregator,
CancellationTokenSource cancellationTokenSource)
: base(test, messageBus, testClass, constructorArguments, testMethod, testMethodArguments, beforeAfterAttributes, aggregator, cancellationTokenSource)
{
lock(typeof(BenchmarkTestInvoker))
{
if (!_initialized)
{
_runId = Environment.GetEnvironmentVariable("XUNIT_PERFORMANCE_RUN_ID");
if (string.IsNullOrEmpty(_runId))
_runId = Environment.MachineName + ":" + DateTimeOffset.UtcNow.ToString("u");
var etwLogPath = Environment.GetEnvironmentVariable("XUNIT_PERFORMANCE_ETL_PATH");
if (etwLogPath == null)
etwLogPath = "xunit.performance.etl";
else if (!ETWLogging.CanLog)
_loggingFailed = true;
if (ETWLogging.CanLog)
_etwLogger = ETWLogging.Start(etwLogPath, _runId);
_initialized = true;
}
}
}
protected override object CallTestMethod(object testClassInstance)
{
if (_loggingFailed)
throw new Exception("ETW logging was requested, but this process is not running with elevated permissions.");
return IterateAsync(testClassInstance);
}
private async Task IterateAsync(object testClassInstance)
{
var benchmarkTestCase = (BenchmarkTestCase)TestCase;
var invoker = MakeInvokerDelegate(testClassInstance);
var asyncSyncContext = (AsyncTestSyncContext)SynchronizationContext.Current;
Stopwatch iterationTimer = new Stopwatch();
Stopwatch overallTimer = new Stopwatch();
RunningStatistics stats = new RunningStatistics();
long totalMemoryAfterWarmup = 0;
int gcCountAfterWarmup = 0;
var allocatesAttribute = TestCase.TestMethod.Method.GetCustomAttributes(typeof(AllocatesAttribute)).FirstOrDefault();
var allocates = (bool?)allocatesAttribute?.GetConstructorArguments().First();
for (int i = 0; ; i++)
{
double elapsedMilliseconds = 0;
if (i != 0 || !benchmarkTestCase.SkipWarmup)
{
bool success = false;
BenchmarkEventSource.Log.BenchmarkExecutionStart(_runId, DisplayName, i);
iterationTimer.Start();
try
{
object result = invoker();
var task = result as Task;
if (task != null)
{
await task;
success = true;
}
else
{
var ex = await asyncSyncContext.WaitForCompletionAsync();
if (ex == null)
success = true;
else
Aggregator.Add(ex);
}
}
finally
{
iterationTimer.Stop();
elapsedMilliseconds = iterationTimer.Elapsed.TotalMilliseconds;
BenchmarkEventSource.Log.BenchmarkExecutionStop(_runId, DisplayName, i, success);
}
if (!success)
break;
}
if (i == 0)
{
totalMemoryAfterWarmup = GC.GetTotalMemory(forceFullCollection: !allocates.HasValue || allocates.Value);
gcCountAfterWarmup = GC.CollectionCount(0);
overallTimer.Start();
}
else
{
stats.Push(elapsedMilliseconds);
//
// Keep running iterations until we've reached the desired margin of error in the result.
//
if (stats.MarginOfError(benchmarkTestCase.Confidence) < benchmarkTestCase.MarginOfError)
{
//
// If the test says it doesn't use the GC, we can stop now.
//
if (allocates.HasValue && !allocates.Value)
break;
//
// If a GC ocurred during the iterations so far, then we've accounted for that in the result,
// and can stop now.
//
if (GC.CollectionCount(0) > gcCountAfterWarmup)
{
if (allocates.HasValue && !allocates.Value)
throw new Exception("Allocated detected in a method that declares no allocation.");
else
break;
}
//
// If the test has not stated whether it uses the GC, we need to guess.
//
if (!allocates.HasValue)
{
//
// Maybe the method allocates, but we haven't executed enough iterations for this to trigger
// the GC. If so, we're missing a large part of the cost of the method. But, some methods will
// never allocate, and so will never trigger a GC. So we need to give up if it looks like nobody
// is allocating anything.
//
// (We can't *just* check GC.GetTotalMemory, because it's only updated when each thread's
// "allocation context" is exhausted. So we make sure to run for a while before trusting
// GC.GetTotalMemory.)
//
if (i >= 1024 && GC.GetTotalMemory(false) == totalMemoryAfterWarmup)
break;
//
// If the iterations so far have taken a significant amount of time, and yet a GC has not occurred,
// we give up and assume that the GC isn't going to be a significant factor for this method.
//
if (overallTimer.Elapsed.TotalSeconds >= 1)
break;
}
else if (!allocates.Value)
{
if (GC.GetTotalMemory(false) != totalMemoryAfterWarmup)
throw new Exception("Allocated detected in a method that declares no allocation.");
}
}
}
}
}
/// <summary>
/// Make a delegate that invokes the test method with this case's arguments. The idea is that invoking the delegate
/// will be faster than using MethodInfo.Invoke, which may matter if we're running a lot of small iterations of the method.
/// </summary>
/// <param name="testClassInstance"></param>
/// <returns></returns>
private Func<object> MakeInvokerDelegate(object testClassInstance)
{
object[] args;
Type[] types;
var testMethodParamTypes = TestMethod.GetParameters().Select(p => p.ParameterType).ToArray();
if (testClassInstance == null)
{
args = TestMethodArguments;
types = testMethodParamTypes;
}
else
{
args = new object[TestMethodArguments.Length + 1];
types = new Type[TestMethodArguments.Length + 1];
args[0] = testClassInstance;
types[0] = testClassInstance.GetType();
Array.Copy(TestMethodArguments, 0, args, 1, TestMethodArguments.Length);
Array.Copy(testMethodParamTypes, 0, types, 1, testMethodParamTypes.Length);
}
if (args.Length == 0)
return MakeInvoker0();
string invokerFactoryName;
switch (args.Length)
{
case 1: invokerFactoryName = nameof(MakeInvoker1); break;
case 2: invokerFactoryName = nameof(MakeInvoker2); break;
case 3: invokerFactoryName = nameof(MakeInvoker3); break;
case 4: invokerFactoryName = nameof(MakeInvoker4); break;
default: return () => TestMethod.Invoke(testClassInstance, TestMethodArguments);
}
var invokerFactory = typeof(BenchmarkTestInvoker).GetMethod(invokerFactoryName, BindingFlags.Instance | BindingFlags.NonPublic);
var invokerFactoryInstance = invokerFactory.MakeGenericMethod(types);
return (Func<object>)invokerFactoryInstance.Invoke(this, args);
}
private Func<object> MakeInvoker0()
{
if (TestMethod.ReturnType == typeof(void))
{
var action = (Action)TestMethod.CreateDelegate(typeof(Action));
return () => { action(); return null; };
}
else
{
return (Func<object>)TestMethod.CreateDelegate(typeof(Func<object>));
}
}
private Func<object> MakeInvoker1<T>(T arg)
{
if (TestMethod.ReturnType == typeof(void))
{
var action = (Action<T>)TestMethod.CreateDelegate(typeof(Action<T>));
return () => { action(arg); return null; };
}
else
{
var func = (Func<T, object>)TestMethod.CreateDelegate(typeof(Func<T, object>));
return () => func(arg);
}
}
private Func<object> MakeInvoker2<T1, T2>(T1 arg1, T2 arg2)
{
if (TestMethod.ReturnType == typeof(void))
{
var action = (Action<T1, T2>)TestMethod.CreateDelegate(typeof(Action<T1, T2>));
return () => { action(arg1, arg2); return null; };
}
else
{
var func = (Func<T1, T2, object>)TestMethod.CreateDelegate(typeof(Func<T1, T2, object>));
return () => func(arg1, arg2);
}
}
private Func<object> MakeInvoker3<T1, T2, T3>(T1 arg1, T2 arg2, T3 arg3)
{
if (TestMethod.ReturnType == typeof(void))
{
var action = (Action<T1, T2, T3>)TestMethod.CreateDelegate(typeof(Action<T1, T2, T3>));
return () => { action(arg1, arg2, arg3); return null; };
}
else
{
var func = (Func<T1, T2, T3, object>)TestMethod.CreateDelegate(typeof(Func<T1, T2, T3, object>));
return () => func(arg1, arg2, arg3);
}
}
private Func<object> MakeInvoker4<T1, T2, T3, T4>(T1 arg1, T2 arg2, T3 arg3, T4 arg4)
{
if (TestMethod.ReturnType == typeof(void))
{
var action = (Action<T1, T2, T3, T4>)TestMethod.CreateDelegate(typeof(Action<T1, T2, T3, T4>));
return () => { action(arg1, arg2, arg3, arg4); return null; };
}
else
{
var func = (Func<T1, T2, T3, T4, object>)TestMethod.CreateDelegate(typeof(Func<T1, T2, T3, T4, object>));
return () => func(arg1, arg2, arg3, arg4);
}
}
/// <summary>
/// Computes whether we've executed enough iterations to have the desired margin of error, with the desired confidence.
/// </summary>
/// <param name="stats"></param>
/// <param name="marginOfError"></param>
/// <param name="confidence"></param>
/// <returns></returns>
private bool HaveDesiredMarginOfError(RunningStatistics stats, double marginOfError, double confidence)
{
if (stats.Count < 2)
return false;
var stderr = stats.StandardDeviation / Math.Sqrt(stats.Count);
var t = MathNet.Numerics.ExcelFunctions.TInv(1.0 - confidence, (int)stats.Count - 1);
var mean = stats.Mean;
var interval = t * stderr;
return (interval / mean) < marginOfError;
}
}
}