-
Notifications
You must be signed in to change notification settings - Fork 23
/
Copy pathBenchmarkRunner.cs
302 lines (240 loc) · 9.86 KB
/
BenchmarkRunner.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
using EdgeDB.Net.IMDBench.Benchmarks;
using EdgeDB.Net.IMDBench.Benchmarks.EdgeDB.Models;
using Humanizer;
using Newtonsoft.Json;
using Newtonsoft.Json.Serialization;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
namespace EdgeDB.Net.IMDBench
{
internal class BenchmarkRunner
{
public static Dictionary<string, Dictionary<string, BaseBenchmark>> AllBenchmarks { get; }
private readonly BenchmarkConfig _config;
private readonly DefaultContractResolver _contractResolver;
static BenchmarkRunner()
{
// discover all benchmarks
var benchmarks = Assembly.GetExecutingAssembly().DefinedTypes.Where(x =>
{
return !x.IsAbstract && x.IsAssignableTo(typeof(BaseBenchmark));
});
AllBenchmarks = new();
// create instances and store them
foreach(var benchmark in benchmarks)
{
var inst = (BaseBenchmark)Activator.CreateInstance(benchmark)!;
AllBenchmarks.TryAdd(inst.Category, new());
AllBenchmarks[inst.Category] ??= new();
AllBenchmarks[inst.Category][inst.Name] = inst;
}
}
public BenchmarkRunner(BenchmarkConfig config)
{
_config = config;
_contractResolver = new()
{
NamingStrategy = new SnakeCaseNamingStrategy()
};
}
public async Task SetupAsync()
{
var benchmarks = GetActiveBenchmarks();
#if DEBUG
Console.WriteLine($"Setting up {benchmarks.Length} benchmarks...");
#endif
for(int i = 0; i != benchmarks.Length; i++)
{
var benchmark = benchmarks[i];
#if DEBUG
Console.WriteLine("Setting up benchmark {0}/{1}: {2}", i + 1, benchmarks.Length, benchmark);
#endif
await benchmark.SetupAsync(_config);
}
#if DEBUG
Console.WriteLine("Setup complete");
#endif
}
public async Task WarmupAsync()
{
var benchmarks = GetActiveBenchmarks();
#if DEBUG
Console.WriteLine($"Starting warmup with {benchmarks.Count()} benchmarks with a duration of {_config.Warmup}s");
#endif
for (int i = 0; i < benchmarks.Length; i++)
{
var benchmark = benchmarks[i];
try
{
#if DEBUG
Console.WriteLine("Warming up benchmark {0}/{1}: {2}", i + 1, benchmarks.Length, benchmark);
var results = await RunManyAsync(_config.Concurrency, () => BenchAsync(benchmark, _config.Warmup, _config.NumSamples));
var stats = new BenchStats(_config.Timeout, results);
Console.WriteLine("{0}: Avg: {1}μs Min: {2}μs Max: {3}μs", benchmark, stats.Average, stats.Min, stats.Max);
#else
await RunManyAsync(_config.Concurrency, () => BenchAsync(benchmark, _config.Warmup));
#endif
}
catch (Exception x)
{
Console.Error.WriteLine($"Exception in {benchmark.Category}.{benchmark.Name}: {x.GetType()} {x}\nState: {benchmark.GetInUseIdsState()}");
#if RELEASE
Environment.Exit(1);
#endif
}
}
#if DEBUG
Console.WriteLine("Cleaning up...");
GC.Collect();
#endif
#if DEBUG
Console.WriteLine("Warmup complete");
#endif
}
public async Task RunAsync()
{
var benchmarks = GetActiveBenchmarks();
#if DEBUG
Console.WriteLine($"Starting benchmarks with {benchmarks.Count()} benchmarks with a duration of {_config.Duration}s");
#endif
for (int i = 0; i < benchmarks.Length; i++)
{
var benchmark = benchmarks[i];
BenchResult[] result;
#if DEBUG
Console.WriteLine("Running benchmark {0}/{1}: {2}", i + 1, benchmarks.Length, benchmark);
#endif
try
{
result = await RunManyAsync(_config.Concurrency, () => BenchAsync(benchmark, _config.Duration, _config.NumSamples));
}
catch (Exception x)
{
Console.Error.WriteLine($"Exception in {benchmark}: {x.GetType()} {x}\nState: {benchmark.GetInUseIdsState()}");
#if RELEASE
Environment.Exit(1);
#endif
continue;
}
var stats = new BenchStats(_config.Timeout, result);
#if RELEASE
// report results of this run
Console.WriteLine(JsonConvert.SerializeObject(stats, new JsonSerializerSettings
{
ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore,
ContractResolver = _contractResolver
}));
#else
Console.WriteLine($"{benchmark.Category}.{benchmark.Name}: Avg: {stats.Average}μs. Min: {stats.Min}μs. Max: {stats.Max}μs.");
#endif
}
}
private Task<TResult[]> RunManyAsync<TResult>(int count, Func<Task<TResult>> func)
{
List<Task<TResult>> tasks = new();
for(int i = 0; i != count; i++)
{
tasks.Add(func());
}
return Task.WhenAll(tasks);
}
private async Task<BenchResult> BenchAsync(BaseBenchmark benchmark, long duration, int sampleCount = 0)
{
var startTime = DateTimeOffset.UtcNow;
var sw = new Stopwatch();
List<object?> samples = new();
List<TimeSpan> times = new();
do
{
var cts = new CancellationTokenSource(TimeSpan.FromSeconds(_config.Timeout));
await benchmark.IterationSetupAsync();
sw.Start();
var task = benchmark.BenchmarkAsync(cts.Token);
await task;
sw.Stop();
cts.Dispose();
// record the sample
if (samples.Count < sampleCount && TryGetTaskResult(task, out var result))
{
samples.Add(result);
}
// add the time
times.Add(sw.Elapsed);
// reset and go again
sw.Reset();
}
while ((DateTimeOffset.UtcNow - startTime).TotalSeconds <= duration);
return new BenchResult(benchmark.Category, benchmark.Name, samples, times, duration);
}
private BaseBenchmark[] GetActiveBenchmarks()
{
return AllBenchmarks
.Where(x => _config.Targets!.Contains(x.Key))
.SelectMany(x => x.Value.Where(y => _config.Queries!.Contains(y.Key)))
.Select(x => x.Value)
.ToArray();
}
private bool TryGetTaskResult(Task task, out object? result)
{
result = null;
var resultProp = task.GetType().GetProperty("Result", BindingFlags.Public | BindingFlags.Instance);
if (resultProp is null)
return false;
result = resultProp.GetValue(task);
return true;
}
private record BenchResult(string Category, string Name, List<object?> Samples, List<TimeSpan> Times, long Duration);
private class BenchStats
{
[JsonProperty("min_latency")]
public double Min { get; }
[JsonProperty("max_latency")]
public double Max { get; }
[JsonProperty("nqueries")]
public long NumQueries { get; }
[JsonProperty("samples")]
public object? Samples { get; }
[JsonProperty("latency_stats")]
public double[] LatencyStats { get; }
[JsonProperty("duration")]
public double Duration { get; }
[JsonProperty("avg_latency")]
public double Average { get; }
public BenchStats(int timeout, BenchResult result)
{
Min = result.Times.Min(x => x.TotalMicroseconds) / 10;
Max = result.Times.Max(x => x.TotalMicroseconds) / 10;
NumQueries = result.Times.Count;
Samples = result.Samples;
LatencyStats = CalculateLatency(timeout, result.Times);
Duration = TimeSpan.FromMicroseconds(result.Times.Sum(x => x.TotalMicroseconds)).TotalSeconds;
Average = result.Times.Average(x => x.TotalMilliseconds);
}
public BenchStats(int timeout, BenchResult[] results)
{
Min = results.Min(result => result.Times.Min(x => x.TotalMicroseconds)) / 10;
Max = results.Min(result => result.Times.Max(x => x.TotalMicroseconds)) / 10;
NumQueries = results.Sum(result => result.Times.Count);
Samples = results.SelectMany(result => result.Samples).ToArray();
LatencyStats = CalculateLatency(timeout, results.SelectMany(x => x.Times));
Duration = TimeSpan.FromMicroseconds(results.Average(result => result.Times.Sum(x => x.TotalMicroseconds))).TotalSeconds;
Average = results.Average(result => result.Times.Average(x => x.TotalMilliseconds));
}
private static double[] CalculateLatency(int timeout, IEnumerable<TimeSpan> times)
{
var mc = times.Select(x => (long)Math.Round(x.TotalMicroseconds / 10));
var arr = new double[(long)Math.Round(TimeSpan.FromSeconds(timeout).TotalMicroseconds / 10)];
foreach (var x in mc)
{
arr[x]++;
}
return arr;
}
}
}
}