-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathBenchmarker.cs
More file actions
227 lines (182 loc) · 7.24 KB
/
Benchmarker.cs
File metadata and controls
227 lines (182 loc) · 7.24 KB
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
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
namespace SharpBenchmark
{
public class Benchmarker
{
private readonly IList<BenchmarkItem> _tests = new List<BenchmarkItem>();
private readonly TextWriter _writer;
private StringBuilder _builder;
private readonly string _fileOutputPath = null;
private double _totalMilliseconds = 0;
private readonly IDictionary<string, BenchmarkResult> _results = new Dictionary<string, BenchmarkResult>();
public Benchmarker(string fileOutputPath) : this()
{
_fileOutputPath = fileOutputPath;
}
public Benchmarker(TextWriter writer) : this()
{
_writer = writer;
}
public Benchmarker()
{
if (_writer == null)
_writer = Console.Out;
}
public double WarmUpPercentage = 0.05;
public bool CopyResultsToClipboard { get; set; }
public void AddTest(string title, Action test)
{
_tests.Add(new BenchmarkItem { Title = title, Test = test });
}
public void RunTests(TimeSpan totalTime)
{
RunWarmUp(1);
InternalRun(null, totalTime);
}
public void RunTests(int minutes, int seconds)
{
RunTests(TimeSpan.FromSeconds((minutes * 60) + seconds));
}
public void RunTests(int num = 100000)
{
RunWarmUp(num);
InternalRun(num, null);
}
private void RunWarmUp(int totalNum)
{
// WARM-UP
// run thru each of them once because otherwise the first loop is slower due to the Just In Time compilation
var numWarmups = Math.Ceiling(totalNum * WarmUpPercentage);
for (var i = 0; i < numWarmups; i++)
{
foreach (var test in _tests)
{
test.Test();
}
}
}
private void InternalRun(int? totalTests, TimeSpan? totalTime)
{
_builder = new StringBuilder();
WriteLine();
if (totalTests.HasValue)
{
WriteLine(String.Format("Running each test {0:#,0} times", totalTests));
}
else
{
WriteLine(String.Format("Running tests for {0}", totalTime));
}
WriteLine();
WriteLine("----------------------------------------------------");
WriteLine("Running tests: ");
if (totalTests.HasValue)
{
for (var i = 0; i < _tests.Count; i++)
{
WriteLine(String.Format(" Pass {0}...", i + 1));
InternalSingleRun(totalTests.Value/_tests.Count);
}
}
else if (totalTime.HasValue)
{
// the batch size will get adjusted based on how long they are taking to process
// we need to start with 1 and then increase based on their speed
var batchSize = 1;
long totalTimesRan = 0;
var batchPercentage = 1.0/(_tests.Count+1);
while (_totalMilliseconds < totalTime.Value.TotalMilliseconds)
{
InternalSingleRun(batchSize);
totalTimesRan += batchSize;
// adjust batch size based on the current pace
var percentDone = _totalMilliseconds/totalTime.Value.TotalMilliseconds;
var estimatedLeft = (totalTimesRan/ percentDone) - totalTimesRan;
// let's be safe and try to split it up into a batch for each test so it gets to run in various order
// batchSize = (int)Math.Floor(estimatedTotalRuns / _tests.Count + 1);
batchSize = (int)Math.Ceiling(estimatedLeft * batchPercentage);
if (batchSize < 1) batchSize = 1;
WriteLine(String.Format(" Running new batch of {0:#,0} tests ({1:0}% complete so far) ...", batchSize, percentDone*100));
// increase the percentage we want to get to for the next batch
// this is used to estimate the number of times we need to run to get to 25%, then 50%, then 75%, etc. (for example)
batchPercentage += 1.0 / (_tests.Count + 1);
}
WriteLine();
WriteLine(String.Format(" Ran {0:#,0} times in time allotted", totalTimesRan));
WriteLine(String.Format(" Took a total of {0}", TimeSpan.FromMilliseconds(_totalMilliseconds)));
}
DisplayResults();
var resultsText = _builder.ToString();
// write to the file if there is one
if (!String.IsNullOrEmpty(_fileOutputPath))
File.WriteAllText(_fileOutputPath, resultsText);
if (CopyResultsToClipboard)
{
OpenClipboard(IntPtr.Zero);
var ptr = Marshal.StringToHGlobalUni(resultsText);
SetClipboardData(13, ptr);
CloseClipboard();
Marshal.FreeHGlobal(ptr);
}
}
private void InternalSingleRun(int num)
{
var sw = new Stopwatch();
foreach (var benchmarkItem in _tests.OrderBy(x => Guid.NewGuid()))
{
sw.Reset();
sw.Start();
for (var i = 0; i < num; i++)
{
benchmarkItem.Test();
}
sw.Stop();
AddResult(benchmarkItem, sw.Elapsed.TotalMilliseconds, num);
}
}
private void DisplayResults()
{
WriteLine();
WriteLine("Results: (fastest first)");
var fastestTime = _results.Values.Min(x => x.TotalTime);
foreach (var item in _results.Values.OrderBy(x => x.TotalTime))
{
WriteLine(item.Display(fastestTime));
WriteLine();
}
WriteLine();
}
private void AddResult(BenchmarkItem item, double totalTime, int timesRun)
{
if (!_results.ContainsKey(item.Title))
{
_results.Add(item.Title, new BenchmarkResult { Title = item.Title, TotalTime = 0.0, TimeRun = 0});
}
var result = _results[item.Title];
result.TimeRun += timesRun;
result.TotalTime += totalTime;
_totalMilliseconds += totalTime;
}
private void WriteLine(string text = "")
{
Write(text + "\r\n");
}
private void Write(string text = "")
{
_writer.Write(text);
_builder.Append(text);
}
[DllImport("user32.dll")]
internal static extern bool OpenClipboard(IntPtr hWndNewOwner);
[DllImport("user32.dll")]
internal static extern bool CloseClipboard();
[DllImport("user32.dll")]
internal static extern bool SetClipboardData(uint uFormat, IntPtr data);
}
}