• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 // Copyright 2014 The Chromium Authors
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
4 
5 #include "components/metrics/histogram_encoder.h"
6 
7 #include <memory>
8 #include <string>
9 
10 #include "base/metrics/histogram.h"
11 #include "base/metrics/histogram_samples.h"
12 #include "base/metrics/metrics_hashes.h"
13 
14 using base::SampleCountIterator;
15 
16 namespace metrics {
17 
EncodeHistogramDelta(const std::string & histogram_name,const base::HistogramSamples & snapshot,ChromeUserMetricsExtension * uma_proto)18 void EncodeHistogramDelta(const std::string& histogram_name,
19                           const base::HistogramSamples& snapshot,
20                           ChromeUserMetricsExtension* uma_proto) {
21   DCHECK_NE(0, snapshot.TotalCount());
22   DCHECK(uma_proto);
23 
24   // We will ignore the MAX_INT/infinite value in the last element of range[].
25 
26   HistogramEventProto* histogram_proto = uma_proto->add_histogram_event();
27   histogram_proto->set_name_hash(base::HashMetricName(histogram_name));
28   if (snapshot.sum() != 0)
29     histogram_proto->set_sum(snapshot.sum());
30 
31   for (std::unique_ptr<SampleCountIterator> it = snapshot.Iterator();
32        !it->Done(); it->Next()) {
33     base::Histogram::Sample min;
34     int64_t max;
35     base::Histogram::Count count;
36     it->Get(&min, &max, &count);
37     HistogramEventProto::Bucket* bucket = histogram_proto->add_bucket();
38     bucket->set_min(min);
39     bucket->set_max(max);
40     // Note: The default for count is 1 in the proto, so omit it in that case.
41     // The iterator also skips over empty buckets, so no need to manually omit
42     // them.
43     if (count != 1)
44       bucket->set_count(count);
45   }
46 
47   // Omit fields to save space (see rules in histogram_event.proto comments).
48   for (int i = 0; i < histogram_proto->bucket_size(); ++i) {
49     HistogramEventProto::Bucket* bucket = histogram_proto->mutable_bucket(i);
50     if (i + 1 < histogram_proto->bucket_size() &&
51         bucket->max() == histogram_proto->bucket(i + 1).min()) {
52       bucket->clear_max();
53     } else if (bucket->max() == bucket->min() + 1) {
54       bucket->clear_min();
55     }
56   }
57 }
58 
59 }  // namespace metrics
60