Skip to content

Commit facd1c3

Browse files
committed
efficient -last count
1 parent 3b5f4e7 commit facd1c3

File tree

2 files changed

+26
-14
lines changed

2 files changed

+26
-14
lines changed

Makefile

+3
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,6 @@
1+
build:
2+
go build myprofiler.go
3+
14
release:
25
GOOS=linux go build myprofiler.go
36
tar cvzf myprofiler.linux_amd64.tar.gz myprofiler

myprofiler.go

+23-14
Original file line numberDiff line numberDiff line change
@@ -77,11 +77,11 @@ func normalizeQuery(query string) string {
7777
return query
7878
}
7979

80-
type pair struct {
80+
type queryCount struct {
8181
q string
8282
c int64
8383
}
84-
type pairList []pair
84+
type pairList []queryCount
8585

8686
func (pl pairList) Len() int {
8787
return len(pl)
@@ -101,9 +101,9 @@ type Summarizer interface {
101101
}
102102

103103
func showSummary(w io.Writer, sum map[string]int64, n int) {
104-
counts := make([]pair, 0, len(sum))
104+
counts := make([]queryCount, 0, len(sum))
105105
for q, c := range sum {
106-
counts = append(counts, pair{q, c})
106+
counts = append(counts, queryCount{q, c})
107107
}
108108
sort.Sort(pairList(counts))
109109

@@ -133,25 +133,34 @@ func (s *summarizer) Show(out io.Writer, num int) {
133133
}
134134

135135
type recentSummarizer struct {
136-
last int
137-
queries [][]string
136+
last int
137+
counts [][]queryCount
138138
}
139139

140140
func (s *recentSummarizer) Update(queries []string) {
141-
if len(s.queries) >= s.last {
142-
s.queries = s.queries[1:]
141+
if len(s.counts) >= s.last {
142+
s.counts = s.counts[1:]
143143
}
144-
s.queries = append(s.queries, queries)
144+
sort.Strings(queries)
145+
qc := make([]queryCount, 0, 16)
146+
for _, q := range queries {
147+
if len(qc) > 0 && qc[len(qc)-1].q == q {
148+
qc[len(qc)-1].c++
149+
} else {
150+
qc = append(qc, queryCount{q: q, c: 1})
151+
}
152+
}
153+
s.counts = append(s.counts, qc)
145154
}
146155

147156
func (s *recentSummarizer) Show(out io.Writer, num int) {
148-
counts := make(map[string]int64)
149-
for _, qs := range s.queries {
150-
for _, q := range qs {
151-
counts[q]++
157+
sum := make(map[string]int64)
158+
for _, qcs := range s.counts {
159+
for _, qc := range qcs {
160+
sum[qc.q] += qc.c
152161
}
153162
}
154-
showSummary(out, counts, num)
163+
showSummary(out, sum, num)
155164
}
156165

157166
func NewSummarizer(last int) Summarizer {

0 commit comments

Comments
 (0)