-
Notifications
You must be signed in to change notification settings - Fork 18
/
Copy pathProgram.cs
314 lines (252 loc) · 10.7 KB
/
Program.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
303
304
305
306
307
308
309
310
311
312
313
314
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Samples.Debugging.MdbgEngine;
using System.Diagnostics;
using System.Threading;
using System.Runtime.InteropServices;
using System.Security.Cryptography;
namespace cpu_analyzer {
class ThreadSnapshotStats {
public long TotalKernelTime { get; set; }
public long TotalUserTime { get; set; }
public int ThreadId { get; set; }
public List<string> CommonStack { get; set; }
public static ThreadSnapshotStats FromSnapshots(IEnumerable<ThreadSnapshot> snapshots) {
ThreadSnapshotStats stats = new ThreadSnapshotStats();
stats.ThreadId = snapshots.First().Id;
stats.TotalKernelTime = snapshots.Last().KernelTime - snapshots.First().KernelTime;
stats.TotalUserTime = snapshots.Last().UserTime - snapshots.First().UserTime;
stats.CommonStack = snapshots.First().StackTrace.ToList();
foreach (var stack in snapshots.Select(_ => _.StackTrace.ToList())) {
while (stats.CommonStack.Count > stack.Count) {
stats.CommonStack.RemoveAt(0);
}
while (stats.CommonStack.Count > 0 && stack.Count > 0 && stats.CommonStack[0] != stack[0]) {
stats.CommonStack.RemoveAt(0);
stack.RemoveAt(0);
}
}
return stats;
}
}
class ThreadSnapshot {
[DllImport("kernel32.dll", CharSet = CharSet.Auto, SetLastError = true)]
private static extern bool GetThreadTimes(IntPtr handle, out long creation, out long exit, out long kernel, out long user);
private ThreadSnapshot ()
{
}
public int Id { get; set; }
public DateTime Time { get; set; }
public long KernelTime { get; set; }
public long UserTime { get; set; }
public List<string> StackTrace {get; set;}
static MD5CryptoServiceProvider md5Provider = new MD5CryptoServiceProvider();
public static Guid GetMD5(string str)
{
lock (md5Provider)
{
return new Guid(md5Provider.ComputeHash(Encoding.Unicode.GetBytes(str)));
}
}
public IEnumerable<Tuple<Guid, string>> StackHashes
{
get
{
List<Tuple<Guid, string>> rval = new List<Tuple<Guid, string>>();
List<string> trace = new List<string>();
foreach (var item in ((IEnumerable<string>)StackTrace).Reverse())
{
trace.Insert(0, item);
var traceString = string.Join(Environment.NewLine, trace);
yield return Tuple.Create(GetMD5(traceString), traceString);
}
}
}
public static ThreadSnapshot GetThreadSnapshot(MDbgThread thread) {
var snapshot = new ThreadSnapshot();
snapshot.Id = thread.Id;
long creation, exit, kernel, user;
GetThreadTimes(thread.CorThread.Handle, out creation, out exit, out kernel, out user);
snapshot.KernelTime = kernel;
snapshot.UserTime = user;
snapshot.StackTrace = new List<string>();
foreach (MDbgFrame frame in thread.Frames) {
try {
snapshot.StackTrace.Add(frame.Function.FullName);
} catch {
// no frame, so ignore
}
}
return snapshot;
}
}
class Program {
enum ParseState {
Unknown, Samples, Interval
}
static void Usage() {
Console.WriteLine("Usage: cpu-analyzer ProcessName|PID [options]");
Console.WriteLine();
Console.WriteLine(" /S indicates how many samples to take (default:10)");
Console.WriteLine(" /I the interval between samples in milliseconds (default:1000)");
Console.WriteLine("");
Console.WriteLine("Example: cpu-analyzer aspnet_wp /s 60 /i 500");
Console.WriteLine(" Take 60 samples once every 500 milliseconds");
}
static void Main(string[] args) {
if (args.Length < 1) {
Usage();
return;
}
int samples = 10;
int sampleInterval = 1000;
var state = ParseState.Unknown;
foreach (var arg in args.Skip(1)) {
switch (state) {
case ParseState.Unknown:
if (arg.ToLower() == "/s") {
state = ParseState.Samples;
} else if (arg.ToLower() == "/i") {
state = ParseState.Interval;
} else {
Usage();
return;
}
break;
case ParseState.Samples:
if (!Int32.TryParse(arg, out samples)) {
Usage();
return;
}
state = ParseState.Unknown;
break;
case ParseState.Interval:
if (!Int32.TryParse(arg, out sampleInterval)) {
Usage();
return;
}
state = ParseState.Unknown;
break;
default:
break;
}
}
string pidOrProcess = args[0];
var stats = new Dictionary<int, List<ThreadSnapshot>>();
var debugger = new MDbgEngine();
int pid = -1;
var processes = Process.GetProcessesByName(pidOrProcess);
if (processes.Length < 1) {
try {
pid = Int32.Parse(pidOrProcess);
} catch {
Console.WriteLine("Error: could not find any processes with that name or pid");
return;
}
} else {
if (processes.Length > 1) {
Console.WriteLine("Warning: multiple processes share that name, attaching to the first");
}
pid = processes[0].Id;
}
MDbgProcess attached = null;
try {
attached = debugger.Attach(pid);
} catch(Exception e) {
Console.WriteLine("Error: failed to attach to process: " + e);
return;
}
attached.Go().WaitOne();
for (int i = 0; i < samples; i++) {
foreach (MDbgThread thread in attached.Threads) {
var snapshot = ThreadSnapshot.GetThreadSnapshot(thread);
List<ThreadSnapshot> snapshots;
if (!stats.TryGetValue(snapshot.Id, out snapshots)) {
snapshots = new List<ThreadSnapshot>();
stats[snapshot.Id] = snapshots;
}
snapshots.Add(snapshot);
}
attached.Go();
Thread.Sleep(sampleInterval);
attached.AsyncStop().WaitOne();
}
attached.Detach().WaitOne();
// perform basic analysis to see which are the top N stack traces observed,
// weighted on cost
Dictionary<Guid, long> costs = new Dictionary<Guid,long>();
Dictionary<Guid, string> stacks = new Dictionary<Guid, string>();
foreach (var stat in stats.Values)
{
long prevTime = -1;
foreach (var snapshot in stat)
{
long time = snapshot.KernelTime + snapshot.UserTime;
if (prevTime != -1)
{
foreach (var tuple in snapshot.StackHashes)
{
if (costs.ContainsKey(tuple.Item1))
{
costs[tuple.Item1] += time - prevTime;
}
else
{
costs[tuple.Item1] = time - prevTime;
stacks[tuple.Item1] = tuple.Item2;
}
}
}
prevTime = time;
}
}
Console.WriteLine("Most expensive stacks");
Console.WriteLine("------------------------------------");
foreach (var group in costs.OrderByDescending(p => p.Value).GroupBy(p => p.Value))
{
List<string> stacksToShow = new List<string>();
foreach (var pair in group.OrderByDescending(p => stacks[p.Key].Length))
{
if (!stacksToShow.Any(s => s.Contains(stacks[pair.Key])))
{
stacksToShow.Add(stacks[pair.Key]);
}
}
foreach (var stack in stacksToShow)
{
Console.WriteLine(stack);
Console.WriteLine("===> Cost ({0})", group.Key);
Console.WriteLine();
}
}
var offenders = stats.Values
.Select(_ => ThreadSnapshotStats.FromSnapshots(_))
.OrderBy(stat => stat.TotalKernelTime + stat.TotalUserTime)
.Reverse();
foreach (var stat in offenders) {
Console.WriteLine("------------------------------------");
Console.WriteLine(stat.ThreadId);
Console.WriteLine("Kernel: {0} User: {1}", stat.TotalKernelTime, stat.TotalUserTime);
foreach (var method in stat.CommonStack) {
Console.WriteLine(method);
}
Console.WriteLine("Other Stacks:");
var prev = new List<string>();
foreach (var trace in stats[stat.ThreadId].Select(_ => _.StackTrace)) {
if (!prev.SequenceEqual(trace)) {
Console.WriteLine();
foreach (var method in trace) {
Console.WriteLine(method);
}
} else {
Console.WriteLine("<skipped>");
}
prev = trace;
}
Console.WriteLine("------------------------------------");
}
}
}
}