8000 Use `collections.defaultdict` to speed up metrics counting (#257) · sonlinux/client_python@cce9af5 · GitHub
[go: up one dir, main page]

Skip to content

Commit cce9af5

Browse files
umaxbrian-brazil
authored andcommitted
Use collections.defaultdict to speed up metrics counting (prometheus#257)
1 parent e2a5061 commit cce9af5

File tree

1 file changed

+12
-11
lines changed

1 file changed

+12
-11
lines changed

prometheus_client/multiprocess.py

Lines changed: 12 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,8 @@
22

33
from __future__ import unicode_literals
44

5+
from collections import defaultdict
6+
57
import glob
68
import json
79
import os
@@ -44,39 +46,38 @@ def collect(self):
4446
d.close()
4547

4648
for metric in metrics.values():
47-
samples = {}
49+
samples = defaultdict(float)
4850
buckets = {}
4951
for name, labels, value in metric.samples:
5052
if metric.type == 'gauge':
51-
without_pid = tuple([l for l in labels if l[0] != 'pid'])
53+
without_pid = tuple(l for l in labels if l[0] != 'pid')
5254
if metric._multiprocess_mode == 'min':
53-
samples.setdefault((name, without_pid), value)
54-
if samples[(name, without_pid)] > value:
55+
current = samples.setdefault((name, without_pid), value)
56+
if value < current:
5557
samples[(name, without_pid)] = value
5658
elif metric._multiprocess_mode == 'max':
57-
samples.setdefault((name, without_pid), value)
58-
if samples[(name, without_pid)] < value:
59+
current = samples.setdefault((name, without_pid), value)
60+
if value > current:
5961
samples[(name, without_pid)] = value
6062
elif metric._multiprocess_mode == 'livesum':
61-
samples.setdefault((name, without_pid), 0.0)
6263
samples[(name, without_pid)] += value
6364
else: # all/liveall
6465
samples[(name, labels)] = value
66+
6567
elif metric.type == 'histogram':
66-
bucket = [float(l[1]) for l in labels if l[0] == 'le']
68+
bucket = tuple(float(l[1]) for l in labels if l[0] == 'le')
6769
if bucket:
6870
# _bucket
69-
without_le = tuple([l for l in labels if l[0] != 'le'])
71+
without_le = tuple(l for l in labels if l[0] != 'le')
7072
buckets.setdefault(without_le, {})
7173
buckets[without_le].setdefault(bucket[0], 0.0)
7274
buckets[without_le][bucket[0]] += value
7375
else:
7476
# _sum/_count
75-
samples.setdefault((name, labels), 0.0)
7677
samples[(name, labels)] += value
78+
7779
else:
7880
# Counter and Summary.
79-
samples.setdefault((name, labels), 0.0)
8081
samples[(name, labels)] += value
8182

8283
# Accumulate bucket values.

0 commit comments

Comments
 (0)
0