sample_map.cc revision 0d205d712abd16eeed2f5d5b1052a367d23a223f
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 9namespace base { 10 11typedef HistogramBase::Count Count; 12typedef HistogramBase::Sample Sample; 13 14SampleMap::SampleMap() : SampleMap(0) {} 15 16SampleMap::SampleMap(uint64_t id) : HistogramSamples(id) {} 17 18SampleMap::~SampleMap() {} 19 20void SampleMap::Accumulate(Sample value, Count count) { 21 sample_counts_[value] += count; 22 IncreaseSum(count * value); 23 IncreaseRedundantCount(count); 24} 25 26Count 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 33Count SampleMap::TotalCount() const { 34 Count count = 0; 35 for (const auto& entry : sample_counts_) { 36 count += entry.second; 37 } 38 return count; 39} 40 41scoped_ptr<SampleCountIterator> SampleMap::Iterator() const { 42 return scoped_ptr<SampleCountIterator>(new SampleMapIterator(sample_counts_)); 43} 44 45bool 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 60SampleMapIterator::SampleMapIterator(const SampleToCountMap& sample_counts) 61 : iter_(sample_counts.begin()), 62 end_(sample_counts.end()) { 63 SkipEmptyBuckets(); 64} 65 66SampleMapIterator::~SampleMapIterator() {} 67 68bool SampleMapIterator::Done() const { 69 return iter_ == end_; 70} 71 72void SampleMapIterator::Next() { 73 DCHECK(!Done()); 74 ++iter_; 75 SkipEmptyBuckets(); 76} 77 78void 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 88void SampleMapIterator::SkipEmptyBuckets() { 89 while (!Done() && iter_->second == 0) { 90 ++iter_; 91 } 92} 93 94} // namespace base 95