1 // Copyright (c) 2012 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
5 #include "base/metrics/sample_map.h"
6
7 #include "base/logging.h"
8
9 namespace base {
10
11 typedef HistogramBase::Count Count;
12 typedef HistogramBase::Sample Sample;
13
SampleMap()14 SampleMap::SampleMap() : SampleMap(0) {}
15
SampleMap(uint64_t id)16 SampleMap::SampleMap(uint64_t id) : HistogramSamples(id) {}
17
~SampleMap()18 SampleMap::~SampleMap() {}
19
Accumulate(Sample value,Count count)20 void SampleMap::Accumulate(Sample value, Count count) {
21 sample_counts_[value] += count;
22 IncreaseSum(count * value);
23 IncreaseRedundantCount(count);
24 }
25
GetCount(Sample value) const26 Count SampleMap::GetCount(Sample value) const {
27 std::map<Sample, Count>::const_iterator it = sample_counts_.find(value);
28 if (it == sample_counts_.end())
29 return 0;
30 return it->second;
31 }
32
TotalCount() const33 Count SampleMap::TotalCount() const {
34 Count count = 0;
35 for (const auto& entry : sample_counts_) {
36 count += entry.second;
37 }
38 return count;
39 }
40
Iterator() const41 scoped_ptr<SampleCountIterator> SampleMap::Iterator() const {
42 return scoped_ptr<SampleCountIterator>(new SampleMapIterator(sample_counts_));
43 }
44
AddSubtractImpl(SampleCountIterator * iter,HistogramSamples::Operator op)45 bool SampleMap::AddSubtractImpl(SampleCountIterator* iter,
46 HistogramSamples::Operator op) {
47 Sample min;
48 Sample max;
49 Count count;
50 for (; !iter->Done(); iter->Next()) {
51 iter->Get(&min, &max, &count);
52 if (min + 1 != max)
53 return false; // SparseHistogram only supports bucket with size 1.
54
55 sample_counts_[min] += (op == HistogramSamples::ADD) ? count : -count;
56 }
57 return true;
58 }
59
SampleMapIterator(const SampleToCountMap & sample_counts)60 SampleMapIterator::SampleMapIterator(const SampleToCountMap& sample_counts)
61 : iter_(sample_counts.begin()),
62 end_(sample_counts.end()) {
63 SkipEmptyBuckets();
64 }
65
~SampleMapIterator()66 SampleMapIterator::~SampleMapIterator() {}
67
Done() const68 bool SampleMapIterator::Done() const {
69 return iter_ == end_;
70 }
71
Next()72 void SampleMapIterator::Next() {
73 DCHECK(!Done());
74 ++iter_;
75 SkipEmptyBuckets();
76 }
77
Get(Sample * min,Sample * max,Count * count) const78 void SampleMapIterator::Get(Sample* min, Sample* max, Count* count) const {
79 DCHECK(!Done());
80 if (min != NULL)
81 *min = iter_->first;
82 if (max != NULL)
83 *max = iter_->first + 1;
84 if (count != NULL)
85 *count = iter_->second;
86 }
87
SkipEmptyBuckets()88 void SampleMapIterator::SkipEmptyBuckets() {
89 while (!Done() && iter_->second == 0) {
90 ++iter_;
91 }
92 }
93
94 } // namespace base
95