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
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
use std::sync::Mutex;
use std::sync::atomic::{AtomicBool, Ordering};
use std::collections::BTreeMap;
use std::time::Duration;
use std::cell::RefCell;
use once_cell::sync::Lazy;
use quanta::Clock;
use petgraph::graph::{Graph, NodeIndex};
use crate::{CallSite, CallSiteId};
static CLOCK: Lazy<Clock> = Lazy::new(Clock::new);
static CALL_GRAPH: Lazy<Mutex<LightCallGraph>> = Lazy::new(|| {
Mutex::new(LightCallGraph::new())
});
static COLLECTION_ENABLED: AtomicBool = AtomicBool::new(false);
thread_local! {
pub static LOCAL_CURRENT_SPAN: RefCell<Option<CallSiteId>> = RefCell::new(None);
}
pub struct Span {
callsite: &'static CallSite,
}
impl Span {
pub fn new(callsite: &'static CallSite) -> Span {
Span {
callsite: callsite,
}
}
#[must_use]
pub fn enter(&self) -> SpanGuard<'_> {
if !COLLECTION_ENABLED.load(Ordering::Acquire) {
return SpanGuard {
span: self,
parent: None,
start: 0,
};
}
let id = self.callsite.id();
let parent = LOCAL_CURRENT_SPAN.with(|parent| {
let mut parent = parent.borrow_mut();
let previous = *parent;
*parent = Some(id);
return previous;
});
SpanGuard {
span: self,
parent: parent,
start: CLOCK.start(),
}
}
}
pub struct SpanGuard<'a> {
span: &'a Span,
parent: Option<CallSiteId>,
start: u64,
}
impl<'a> Drop for SpanGuard<'a> {
fn drop(&mut self) {
if !COLLECTION_ENABLED.load(Ordering::Acquire) {
return;
}
let elapsed = CLOCK.delta(self.start, CLOCK.end());
LOCAL_CURRENT_SPAN.with(|parent| {
let mut parent = parent.borrow_mut();
*parent = self.parent;
});
let mut graph = CALL_GRAPH.lock().expect("poisoned mutex");
let callsite = self.span.callsite.id();
graph.add_node(callsite);
graph.increase_timing(callsite, elapsed);
if let Some(parent) = self.parent {
graph.add_node(parent);
graph.increase_call_count(parent, callsite);
}
}
}
struct LightGraphNode {
callsite: CallSiteId,
elapsed: Duration,
called: u32,
}
impl LightGraphNode {
fn new(callsite: CallSiteId) -> LightGraphNode {
LightGraphNode {
callsite: callsite,
elapsed: Duration::new(0, 0),
called: 0,
}
}
}
struct LightCallGraph {
graph: Graph<LightGraphNode, usize>
}
impl LightCallGraph {
fn new() -> LightCallGraph {
LightCallGraph {
graph: Graph::new(),
}
}
pub fn clear(&mut self) {
self.graph.clear()
}
fn find(&mut self, callsite: CallSiteId) -> Option<NodeIndex> {
for id in self.graph.node_indices() {
if self.graph[id].callsite == callsite {
return Some(id);
}
}
return None;
}
pub fn add_node(&mut self, callsite: CallSiteId) {
if self.find(callsite).is_none() {
self.graph.add_node(LightGraphNode::new(callsite));
}
}
pub fn increase_call_count(&mut self, parent: CallSiteId, child: CallSiteId) {
let parent = self.find(parent).expect("missing node for parent");
let child = self.find(child).expect("missing node for child");
if let Some(edge) = self.graph.find_edge(parent, child) {
let count = self
.graph
.edge_weight_mut(edge)
.expect("failed to get edge weights");
*count += 1;
} else {
self.graph.add_edge(parent, child, 1);
}
}
pub fn increase_timing(&mut self, span: CallSiteId, time: Duration) {
let id = self.find(span).expect("missing node");
self.graph[id].elapsed += time;
self.graph[id].called += 1;
}
}
pub fn clear_collected_data() {
CALL_GRAPH.lock().expect("poisoned mutex").clear();
}
pub fn enable_data_collection(enabled: bool) {
COLLECTION_ENABLED.store(enabled, Ordering::Release);
}
pub fn get_full_graph() -> FullCallGraph {
let graph = CALL_GRAPH.lock().expect("poisoned mutex");
let mut all_callsites = BTreeMap::new();
crate::traverse_registered_callsite(|callsite| {
all_callsites.insert(callsite.id(), callsite);
});
let graph = graph.graph.map(|index, node| {
TimedSpan::new(node, index.index(), all_callsites[&node.callsite])
}, |_, &edge| edge);
return FullCallGraph {
graph: graph
};
}
pub struct TimedSpan {
pub id: usize,
pub callsite: &'static CallSite,
pub elapsed: Duration,
pub called: u32,
}
impl TimedSpan {
fn new(node: &LightGraphNode, id: usize, callsite: &'static CallSite) -> TimedSpan {
TimedSpan {
id: id,
callsite: callsite,
elapsed: node.elapsed,
called: node.called,
}
}
}
impl std::fmt::Display for TimedSpan {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(
f,
"{} ran for {:?}, called {} times",
self.callsite.full_name(), self.elapsed, self.called
)
}
}
pub struct FullCallGraph {
graph: Graph<TimedSpan, usize>
}
pub struct Calls {
pub caller: usize,
pub callee: usize,
pub count: usize,
}
impl FullCallGraph {
pub fn spans(&self) -> impl Iterator<Item = &TimedSpan> {
self.graph.raw_nodes().iter().map(|node| &node.weight)
}
pub fn calls(&self) -> impl Iterator<Item = Calls> + '_ {
self.graph.raw_edges().iter().map(|edge| Calls {
caller: edge.target().index(),
callee: edge.source().index(),
count: edge.weight,
})
}
pub fn as_dot(&self) -> String {
petgraph::dot::Dot::new(&self.graph).to_string()
}
#[cfg(feature = "table")]
pub fn as_table(&self) -> String {
self.as_table_impl(false)
}
#[cfg(feature = "table")]
pub fn as_short_table(&self) -> String {
self.as_table_impl(true)
}
#[cfg(feature = "table")]
fn as_table_impl(&self, short_names: bool) -> String {
use petgraph::Direction;
use term_table::row::Row;
use term_table::table_cell::{Alignment, TableCell};
let mut names = BTreeMap::new();
for node in self.graph.node_weights() {
if short_names {
names.insert(node.id, node.callsite.name().to_string());
} else {
names.insert(node.id, node.callsite.full_name());
}
}
let mut table = term_table::Table::new();
table.style = term_table::TableStyle::extended();
table.add_row(Row::new(vec![
"id",
"span name ",
"call count",
"called by",
"total",
"mean",
]));
for &node_id in petgraph::algo::kosaraju_scc(&self.graph)
.iter()
.rev()
.flatten()
{
let node = &self.graph[node_id];
let mut called_by = vec![];
for other in self.graph.neighbors_directed(node_id, Direction::Incoming) {
called_by.push(self.graph[other].id.to_string());
}
let called_by = if !called_by.is_empty() {
called_by.join(", ")
} else {
"—".into()
};
let mean = node.elapsed / node.called;
let warn = if mean < Duration::from_nanos(1500) { " ⚠️ " } else { "" };
table.add_row(Row::new(vec![
TableCell::new_with_alignment(node.id, 1, Alignment::Right),
TableCell::new(&names[&node.id]),
TableCell::new_with_alignment(node.called, 1, Alignment::Right),
TableCell::new_with_alignment(called_by, 1, Alignment::Right),
TableCell::new_with_alignment(
&format!("{:.2?}", node.elapsed),
1,
Alignment::Right,
),
TableCell::new_with_alignment(
&format!("{:.2?}{}", mean, warn),
1,
Alignment::Right,
),
]));
}
return table.render();
}
#[cfg(feature = "json")]
pub fn as_json(&self) -> String {
let mut spans = json::JsonValue::new_object();
for span in self.spans() {
spans[&span.callsite.full_name()] = json::object! {
"id" => span.id,
"elapsed" => format!("{:?}", span.elapsed),
"called" => span.called,
};
}
let mut all_calls = json::JsonValue::new_array();
for call in self.calls() {
all_calls.push(json::object! {
"caller" => call.caller,
"callee" => call.callee,
"count" => call.count,
}).expect("failed to add edge information to JSON");
}
return json::stringify(json::object! {
"timings" => spans,
"calls" => all_calls,
});
}
}