Aggregate merges similar goroutines into buckets. The buckets are ordered in library provided order of relevancy. You can reorder at your choosing.
(similar Similarity)
| 40 | // The buckets are ordered in library provided order of relevancy. You can |
| 41 | // reorder at your choosing. |
| 42 | func (s *Snapshot) Aggregate(similar Similarity) *Aggregated { |
| 43 | type count struct { |
| 44 | ids []int |
| 45 | first bool |
| 46 | } |
| 47 | b := map[*Signature]*count{} |
| 48 | // O(n²). Fix eventually. |
| 49 | for _, routine := range s.Goroutines { |
| 50 | found := false |
| 51 | for key, c := range b { |
| 52 | // When a match is found, this effectively drops the other goroutine ID. |
| 53 | if key.similar(&routine.Signature, similar) { |
| 54 | found = true |
| 55 | c.ids = append(c.ids, routine.ID) |
| 56 | c.first = c.first || routine.First |
| 57 | if !key.equal(&routine.Signature) { |
| 58 | // Almost but not quite equal. There's different pointers passed |
| 59 | // around but the same values. Zap out the different values. |
| 60 | newKey := key.merge(&routine.Signature) |
| 61 | b[newKey] = c |
| 62 | delete(b, key) |
| 63 | } |
| 64 | break |
| 65 | } |
| 66 | } |
| 67 | if !found { |
| 68 | // Create a copy of the Signature, since it will be mutated. |
| 69 | key := &Signature{} |
| 70 | *key = routine.Signature |
| 71 | b[key] = &count{ids: []int{routine.ID}, first: routine.First} |
| 72 | } |
| 73 | } |
| 74 | bs := make([]*Bucket, 0, len(b)) |
| 75 | for signature, c := range b { |
| 76 | sort.Ints(c.ids) |
| 77 | bs = append(bs, &Bucket{Signature: *signature, IDs: c.ids, First: c.first}) |
| 78 | } |
| 79 | // Do reverse sort. |
| 80 | sort.SliceStable(bs, func(i, j int) bool { |
| 81 | l := bs[i] |
| 82 | r := bs[j] |
| 83 | if l.First || r.First { |
| 84 | return l.First |
| 85 | } |
| 86 | if l.Signature.less(&r.Signature) { |
| 87 | return true |
| 88 | } |
| 89 | if r.Signature.less(&l.Signature) { |
| 90 | return false |
| 91 | } |
| 92 | return len(r.IDs) > len(l.IDs) |
| 93 | }) |
| 94 | return &Aggregated{ |
| 95 | Snapshot: s, |
| 96 | Buckets: bs, |
| 97 | } |
| 98 | } |
| 99 |