forked from ServiceStack/ServiceStack
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathPerfUtils.cs
More file actions
80 lines (68 loc) · 2.23 KB
/
PerfUtils.cs
File metadata and controls
80 lines (68 loc) · 2.23 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
#if !SL5 && !IOS && !XBOX
using System;
using System.Diagnostics;
namespace ServiceStack
{
public static class PerfUtils
{
public static TimeSpan ToTimeSpan(this long fromTicks)
{
return TimeSpan.FromSeconds(fromTicks * 1d / Stopwatch.Frequency);
}
/// <summary>
/// Runs an action for a minimum of runForMs
/// </summary>
/// <param name="fn">What to run</param>
/// <param name="runForMs">Minimum ms to run for</param>
/// <returns>time elapsed in micro seconds</returns>
public static double MeasureFor(Action fn, int runForMs)
{
int iter = 0;
var watch = new Stopwatch();
watch.Start();
long elapsed = 0;
while (elapsed < runForMs)
{
fn();
elapsed = watch.ElapsedMilliseconds;
iter++;
}
return 1000.0 * elapsed / iter;
}
/// <summary>
/// Returns average microseconds an action takes when run for the specified runForMs
/// </summary>
/// <param name="fn">What to run</param>
/// <param name="times">How many times to run for each iteration</param>
/// <param name="runForMs">Minimum ms to run for</param>
/// <param name="setup"></param>
/// <param name="warmup"></param>
/// <param name="teardown"></param>
/// <returns></returns>
public static double Measure(Action fn,
int times = 1,
int runForMs = 2000,
Action setup = null,
Action warmup = null,
Action teardown = null)
{
if (setup != null)
setup();
// Warmup for at least 100ms. Discard result.
if (warmup == null)
warmup = fn;
GC.Collect();
MeasureFor(() => warmup(), 100);
// Run the benchmark for at least 2000ms.
double result = MeasureFor(() =>
{
for (var i = 0; i < times; i++)
fn();
}, runForMs);
if (teardown != null)
teardown();
return result;
}
}
}
#endif