This repository was archived by the owner on May 1, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1.9k
/
Copy pathPerformanceProvider.cs
96 lines (79 loc) · 2.55 KB
/
PerformanceProvider.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
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Runtime.CompilerServices;
using Xamarin.Forms.Internals;
namespace Xamarin.Forms.Build.Tasks
{
[Preserve(AllMembers = true)]
internal class PerformanceProvider : IPerformanceProvider
{
internal class Statistic
{
public readonly List<Tuple<string, long>> StartTimes = new List<Tuple<string, long>>();
public int CallCount;
public long TotalTime;
public bool IsDetail;
}
readonly Dictionary<string, Statistic> _Statistics = new Dictionary<string, Statistic>();
public Dictionary<string, Statistic> Statistics
{
get { return _Statistics; }
}
public void Clear()
{
Statistics.Clear();
}
public void Start(string reference, string tag = null, [CallerFilePath] string path = null, [CallerMemberName] string member = null)
{
string id = GetId(tag, path, member);
Statistic stats = GetStat(id);
if (tag != null)
stats.IsDetail = true;
stats.CallCount++;
stats.StartTimes.Add(new Tuple<string, long>(reference, Stopwatch.GetTimestamp()));
}
public void Stop(string reference, string tag = null, [CallerFilePath] string path = null, [CallerMemberName] string member = null)
{
string id = GetId(tag, path, member);
long stop = Stopwatch.GetTimestamp();
Statistic stats = GetStat(id);
if (!stats.StartTimes.Any())
return;
long start = stats.StartTimes.Single(s => s.Item1 == reference).Item2;
stats.TotalTime += stop - start;
}
public IEnumerable<string> GetStats()
{
yield return "ID | Call Count | Total Time | Avg Time";
foreach (KeyValuePair<string, Statistic> kvp in Statistics.OrderBy(kvp => kvp.Key))
{
string key = ShortenPath(kvp.Key);
double total = TimeSpan.FromTicks(kvp.Value.TotalTime).TotalMilliseconds;
double avg = total / kvp.Value.CallCount;
yield return string.Format("{0,-80} | {1,-10} | {2,-10}ms | {3,-8}ms", key, kvp.Value.CallCount, total, avg);
}
}
static string ShortenPath(string path)
{
int index = path.IndexOf("Xamarin.Forms.");
if (index > -1)
path = path.Substring(index + 14);
return path;
}
static string GetId(string tag, string path, string member)
{
return string.Format("{0}:{1}{2}", path, member, (tag != null ? "-" + tag : string.Empty));
}
Statistic GetStat(string id)
{
Statistic stats;
if (!Statistics.TryGetValue(id, out stats))
{
Statistics[id] = stats = new Statistic();
}
return stats;
}
}
}