histogram_encoder.cc 1.9 KB

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