-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathExtensions.Diagnostics.cs
More file actions
47 lines (43 loc) · 1.48 KB
/
Extensions.Diagnostics.cs
File metadata and controls
47 lines (43 loc) · 1.48 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
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace SharpExtensions
{
public static partial class Extensions
{
/// <summary>
/// Force a GC.Collect and measure the execution time of an action.
/// </summary>
public static TimeSpan Measure(this Action action)
{
if (action == null) throw new ArgumentNullException(nameof(action), "An action to measure must be provided");
GC.Collect();
var sw = Stopwatch.StartNew();
try
{
action();
}
catch (Exception)
{
// don't care
}
sw.Stop();
return sw.Elapsed;
}
/// <summary>
/// Get the average execution time of an action after N executions
/// </summary>
public static double MeasureAverage(this Action action, int executions)
{
if (action == null) throw new ArgumentNullException(nameof(action), "An action to measure must be provided");
if (executions < 1) throw new ArgumentOutOfRangeException(nameof(executions), "No of executions must be greater than 1");
var results = new List<double>();
for (int i = 0; i < executions; i++)
results.Add(action.Measure().TotalMilliseconds);
return results.Average();
}
}
}