@@ -11,3 +11,66 @@ struct sample {
11
11
12
12
std::map<uintptr_t , sample> flapmap;
13
13
using flapmap_iter = std::map<uintptr_t , sample>::iterator;
14
+
15
+ void add_sample (uintptr_t start, size_t duration, size_t flapcount) {
16
+ sample s = {start, duration, flapcount};
17
+ flapmap[start] = s;
18
+ flapmap_iter it = flapmap.find (start);
19
+ while (can_coalesce_down (it)) {
20
+ --it;
21
+ }
22
+
23
+ while (can_coalesce_up (it)) {
24
+ coalesce_up ();
25
+ }
26
+
27
+ }
28
+
29
+ bool has_sample (uintptr_t t) {
30
+ if (flapmap.empty ()) {
31
+ return false ;
32
+ }
33
+ flapmap_iter it = flapmap.upper_bound (t); // nearest start greater than t
34
+ if (it != flapmap.begin ()) {
35
+ --it;
36
+ }
37
+ return (it->second .start <= t) && (it->second .start + it->second .duration > t);
38
+ }
39
+
40
+ bool can_coalesce_up (flapmap_iter it) {
41
+ assert (it != flapmap.end ());
42
+ flapmap_iter next = it;
43
+ ++next;
44
+ if (next == flapmap.end ()) {
45
+ return false ;
46
+ }
47
+ return it->second .start + it->second .duration == next->second .start ;
48
+ }
49
+
50
+ void coalesce_up (flapmap_iter it) {
51
+ if (can_coalesce_up (it)) {
52
+ flapmap_iter next = it;
53
+ ++next;
54
+ it->second .duration += next->second .duration ;
55
+ it->second .flapcount += next->second .flapcount ;
56
+ flapmap.erase (next);
57
+ }
58
+ }
59
+
60
+ bool can_coalesce_down (flapmap_iter it) {
61
+ assert (it != flapmap.end ());
62
+
63
+ if (it == flapmap.begin ()) {
64
+ return false ;
65
+ }
66
+ flapmap_iter prev = it;
67
+ --prev;
68
+
69
+ return it->second .start == prev->second .start + prev->second .duration ;
70
+ }
71
+
72
+ void print_flapmap () {
73
+ for (flapmap_iter it = flapmap.begin (); it != flapmap.end (); ++it) {
74
+ fprintf (stdout, " key %ld, start %ld, duration %ld, flapcount %ld\n " , it->first , it->second .start , it->second .duration , it->second .flapcount );
75
+ }
76
+ }
0 commit comments