Don't preload rarely seen large images
[chromium-blink-merge.git] / base / metrics / histogram.cc
blob7dfb552844ded907299cbe120b64042c5819bdd1
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.
5 // Histogram is an object that aggregates statistics, and can summarize them in
6 // various forms, including ASCII graphical, HTML, and numerically (as a
7 // vector of numbers corresponding to each of the aggregating buckets).
8 // See header file for details and examples.
10 #include "base/metrics/histogram.h"
12 #include <math.h>
14 #include <algorithm>
15 #include <string>
17 #include "base/compiler_specific.h"
18 #include "base/debug/alias.h"
19 #include "base/logging.h"
20 #include "base/metrics/histogram_macros.h"
21 #include "base/metrics/sample_vector.h"
22 #include "base/metrics/statistics_recorder.h"
23 #include "base/pickle.h"
24 #include "base/strings/string_util.h"
25 #include "base/strings/stringprintf.h"
26 #include "base/synchronization/lock.h"
27 #include "base/values.h"
29 namespace base {
31 namespace {
33 bool ReadHistogramArguments(PickleIterator* iter,
34 std::string* histogram_name,
35 int* flags,
36 int* declared_min,
37 int* declared_max,
38 size_t* bucket_count,
39 uint32* range_checksum) {
40 if (!iter->ReadString(histogram_name) ||
41 !iter->ReadInt(flags) ||
42 !iter->ReadInt(declared_min) ||
43 !iter->ReadInt(declared_max) ||
44 !iter->ReadSizeT(bucket_count) ||
45 !iter->ReadUInt32(range_checksum)) {
46 DLOG(ERROR) << "Pickle error decoding Histogram: " << *histogram_name;
47 return false;
50 // Since these fields may have come from an untrusted renderer, do additional
51 // checks above and beyond those in Histogram::Initialize()
52 if (*declared_max <= 0 ||
53 *declared_min <= 0 ||
54 *declared_max < *declared_min ||
55 INT_MAX / sizeof(HistogramBase::Count) <= *bucket_count ||
56 *bucket_count < 2) {
57 DLOG(ERROR) << "Values error decoding Histogram: " << histogram_name;
58 return false;
61 // We use the arguments to find or create the local version of the histogram
62 // in this process, so we need to clear the IPC flag.
63 DCHECK(*flags & HistogramBase::kIPCSerializationSourceFlag);
64 *flags &= ~HistogramBase::kIPCSerializationSourceFlag;
66 return true;
69 bool ValidateRangeChecksum(const HistogramBase& histogram,
70 uint32 range_checksum) {
71 const Histogram& casted_histogram =
72 static_cast<const Histogram&>(histogram);
74 return casted_histogram.bucket_ranges()->checksum() == range_checksum;
77 } // namespace
79 typedef HistogramBase::Count Count;
80 typedef HistogramBase::Sample Sample;
82 // static
83 const size_t Histogram::kBucketCount_MAX = 16384u;
85 HistogramBase* Histogram::FactoryGet(const std::string& name,
86 Sample minimum,
87 Sample maximum,
88 size_t bucket_count,
89 int32 flags) {
90 bool valid_arguments =
91 InspectConstructionArguments(name, &minimum, &maximum, &bucket_count);
92 DCHECK(valid_arguments);
94 HistogramBase* histogram = StatisticsRecorder::FindHistogram(name);
95 if (!histogram) {
96 // To avoid racy destruction at shutdown, the following will be leaked.
97 BucketRanges* ranges = new BucketRanges(bucket_count + 1);
98 InitializeBucketRanges(minimum, maximum, ranges);
99 const BucketRanges* registered_ranges =
100 StatisticsRecorder::RegisterOrDeleteDuplicateRanges(ranges);
102 Histogram* tentative_histogram =
103 new Histogram(name, minimum, maximum, registered_ranges);
105 tentative_histogram->SetFlags(flags);
106 histogram =
107 StatisticsRecorder::RegisterOrDeleteDuplicate(tentative_histogram);
110 DCHECK_EQ(HISTOGRAM, histogram->GetHistogramType());
111 if (!histogram->HasConstructionArguments(minimum, maximum, bucket_count)) {
112 // The construction arguments do not match the existing histogram. This can
113 // come about if an extension updates in the middle of a chrome run and has
114 // changed one of them, or simply by bad code within Chrome itself. We
115 // return NULL here with the expectation that bad code in Chrome will crash
116 // on dereference, but extension/Pepper APIs will guard against NULL and not
117 // crash.
118 DLOG(ERROR) << "Histogram " << name << " has bad construction arguments";
119 return NULL;
121 return histogram;
124 HistogramBase* Histogram::FactoryTimeGet(const std::string& name,
125 TimeDelta minimum,
126 TimeDelta maximum,
127 size_t bucket_count,
128 int32 flags) {
129 return FactoryGet(name, static_cast<Sample>(minimum.InMilliseconds()),
130 static_cast<Sample>(maximum.InMilliseconds()), bucket_count,
131 flags);
134 HistogramBase* Histogram::FactoryGet(const char* name,
135 Sample minimum,
136 Sample maximum,
137 size_t bucket_count,
138 int32 flags) {
139 return FactoryGet(std::string(name), minimum, maximum, bucket_count, flags);
142 HistogramBase* Histogram::FactoryTimeGet(const char* name,
143 TimeDelta minimum,
144 TimeDelta maximum,
145 size_t bucket_count,
146 int32 flags) {
147 return FactoryTimeGet(std::string(name), minimum, maximum, bucket_count,
148 flags);
151 // Calculate what range of values are held in each bucket.
152 // We have to be careful that we don't pick a ratio between starting points in
153 // consecutive buckets that is sooo small, that the integer bounds are the same
154 // (effectively making one bucket get no values). We need to avoid:
155 // ranges(i) == ranges(i + 1)
156 // To avoid that, we just do a fine-grained bucket width as far as we need to
157 // until we get a ratio that moves us along at least 2 units at a time. From
158 // that bucket onward we do use the exponential growth of buckets.
160 // static
161 void Histogram::InitializeBucketRanges(Sample minimum,
162 Sample maximum,
163 BucketRanges* ranges) {
164 double log_max = log(static_cast<double>(maximum));
165 double log_ratio;
166 double log_next;
167 size_t bucket_index = 1;
168 Sample current = minimum;
169 ranges->set_range(bucket_index, current);
170 size_t bucket_count = ranges->bucket_count();
171 while (bucket_count > ++bucket_index) {
172 double log_current;
173 log_current = log(static_cast<double>(current));
174 // Calculate the count'th root of the range.
175 log_ratio = (log_max - log_current) / (bucket_count - bucket_index);
176 // See where the next bucket would start.
177 log_next = log_current + log_ratio;
178 Sample next;
179 next = static_cast<int>(floor(exp(log_next) + 0.5));
180 if (next > current)
181 current = next;
182 else
183 ++current; // Just do a narrow bucket, and keep trying.
184 ranges->set_range(bucket_index, current);
186 ranges->set_range(ranges->bucket_count(), HistogramBase::kSampleType_MAX);
187 ranges->ResetChecksum();
190 // static
191 const int Histogram::kCommonRaceBasedCountMismatch = 5;
193 int Histogram::FindCorruption(const HistogramSamples& samples) const {
194 int inconsistencies = NO_INCONSISTENCIES;
195 Sample previous_range = -1; // Bottom range is always 0.
196 for (size_t index = 0; index < bucket_count(); ++index) {
197 int new_range = ranges(index);
198 if (previous_range >= new_range)
199 inconsistencies |= BUCKET_ORDER_ERROR;
200 previous_range = new_range;
203 if (!bucket_ranges()->HasValidChecksum())
204 inconsistencies |= RANGE_CHECKSUM_ERROR;
206 int64 delta64 = samples.redundant_count() - samples.TotalCount();
207 if (delta64 != 0) {
208 int delta = static_cast<int>(delta64);
209 if (delta != delta64)
210 delta = INT_MAX; // Flag all giant errors as INT_MAX.
211 if (delta > 0) {
212 UMA_HISTOGRAM_COUNTS("Histogram.InconsistentCountHigh", delta);
213 if (delta > kCommonRaceBasedCountMismatch)
214 inconsistencies |= COUNT_HIGH_ERROR;
215 } else {
216 DCHECK_GT(0, delta);
217 UMA_HISTOGRAM_COUNTS("Histogram.InconsistentCountLow", -delta);
218 if (-delta > kCommonRaceBasedCountMismatch)
219 inconsistencies |= COUNT_LOW_ERROR;
222 return inconsistencies;
225 Sample Histogram::ranges(size_t i) const {
226 return bucket_ranges_->range(i);
229 size_t Histogram::bucket_count() const {
230 return bucket_ranges_->bucket_count();
233 // static
234 bool Histogram::InspectConstructionArguments(const std::string& name,
235 Sample* minimum,
236 Sample* maximum,
237 size_t* bucket_count) {
238 // Defensive code for backward compatibility.
239 if (*minimum < 1) {
240 DVLOG(1) << "Histogram: " << name << " has bad minimum: " << *minimum;
241 *minimum = 1;
243 if (*maximum >= kSampleType_MAX) {
244 DVLOG(1) << "Histogram: " << name << " has bad maximum: " << *maximum;
245 *maximum = kSampleType_MAX - 1;
247 if (*bucket_count >= kBucketCount_MAX) {
248 DVLOG(1) << "Histogram: " << name << " has bad bucket_count: "
249 << *bucket_count;
250 *bucket_count = kBucketCount_MAX - 1;
253 if (*minimum >= *maximum)
254 return false;
255 if (*bucket_count < 3)
256 return false;
257 if (*bucket_count > static_cast<size_t>(*maximum - *minimum + 2))
258 return false;
259 return true;
262 HistogramType Histogram::GetHistogramType() const {
263 return HISTOGRAM;
266 bool Histogram::HasConstructionArguments(Sample expected_minimum,
267 Sample expected_maximum,
268 size_t expected_bucket_count) const {
269 return ((expected_minimum == declared_min_) &&
270 (expected_maximum == declared_max_) &&
271 (expected_bucket_count == bucket_count()));
274 void Histogram::Add(int value) {
275 DCHECK_EQ(0, ranges(0));
276 DCHECK_EQ(kSampleType_MAX, ranges(bucket_count()));
278 if (value > kSampleType_MAX - 1)
279 value = kSampleType_MAX - 1;
280 if (value < 0)
281 value = 0;
282 samples_->Accumulate(value, 1);
285 scoped_ptr<HistogramSamples> Histogram::SnapshotSamples() const {
286 return SnapshotSampleVector().Pass();
289 void Histogram::AddSamples(const HistogramSamples& samples) {
290 samples_->Add(samples);
293 bool Histogram::AddSamplesFromPickle(PickleIterator* iter) {
294 return samples_->AddFromPickle(iter);
297 // The following methods provide a graphical histogram display.
298 void Histogram::WriteHTMLGraph(std::string* output) const {
299 // TBD(jar) Write a nice HTML bar chart, with divs an mouse-overs etc.
300 output->append("<PRE>");
301 WriteAsciiImpl(true, "<br>", output);
302 output->append("</PRE>");
305 void Histogram::WriteAscii(std::string* output) const {
306 WriteAsciiImpl(true, "\n", output);
309 bool Histogram::SerializeInfoImpl(Pickle* pickle) const {
310 DCHECK(bucket_ranges()->HasValidChecksum());
311 return pickle->WriteString(histogram_name()) &&
312 pickle->WriteInt(flags()) &&
313 pickle->WriteInt(declared_min()) &&
314 pickle->WriteInt(declared_max()) &&
315 pickle->WriteSizeT(bucket_count()) &&
316 pickle->WriteUInt32(bucket_ranges()->checksum());
319 Histogram::Histogram(const std::string& name,
320 Sample minimum,
321 Sample maximum,
322 const BucketRanges* ranges)
323 : HistogramBase(name),
324 bucket_ranges_(ranges),
325 declared_min_(minimum),
326 declared_max_(maximum) {
327 if (ranges)
328 samples_.reset(new SampleVector(ranges));
331 Histogram::~Histogram() {
334 bool Histogram::PrintEmptyBucket(size_t index) const {
335 return true;
338 // Use the actual bucket widths (like a linear histogram) until the widths get
339 // over some transition value, and then use that transition width. Exponentials
340 // get so big so fast (and we don't expect to see a lot of entries in the large
341 // buckets), so we need this to make it possible to see what is going on and
342 // not have 0-graphical-height buckets.
343 double Histogram::GetBucketSize(Count current, size_t i) const {
344 DCHECK_GT(ranges(i + 1), ranges(i));
345 static const double kTransitionWidth = 5;
346 double denominator = ranges(i + 1) - ranges(i);
347 if (denominator > kTransitionWidth)
348 denominator = kTransitionWidth; // Stop trying to normalize.
349 return current/denominator;
352 const std::string Histogram::GetAsciiBucketRange(size_t i) const {
353 return GetSimpleAsciiBucketRange(ranges(i));
356 //------------------------------------------------------------------------------
357 // Private methods
359 // static
360 HistogramBase* Histogram::DeserializeInfoImpl(PickleIterator* iter) {
361 std::string histogram_name;
362 int flags;
363 int declared_min;
364 int declared_max;
365 size_t bucket_count;
366 uint32 range_checksum;
368 if (!ReadHistogramArguments(iter, &histogram_name, &flags, &declared_min,
369 &declared_max, &bucket_count, &range_checksum)) {
370 return NULL;
373 // Find or create the local version of the histogram in this process.
374 HistogramBase* histogram = Histogram::FactoryGet(
375 histogram_name, declared_min, declared_max, bucket_count, flags);
377 if (!ValidateRangeChecksum(*histogram, range_checksum)) {
378 // The serialized histogram might be corrupted.
379 return NULL;
381 return histogram;
384 scoped_ptr<SampleVector> Histogram::SnapshotSampleVector() const {
385 scoped_ptr<SampleVector> samples(new SampleVector(bucket_ranges()));
386 samples->Add(*samples_);
387 return samples.Pass();
390 void Histogram::WriteAsciiImpl(bool graph_it,
391 const std::string& newline,
392 std::string* output) const {
393 // Get local (stack) copies of all effectively volatile class data so that we
394 // are consistent across our output activities.
395 scoped_ptr<SampleVector> snapshot = SnapshotSampleVector();
396 Count sample_count = snapshot->TotalCount();
398 WriteAsciiHeader(*snapshot, sample_count, output);
399 output->append(newline);
401 // Prepare to normalize graphical rendering of bucket contents.
402 double max_size = 0;
403 if (graph_it)
404 max_size = GetPeakBucketSize(*snapshot);
406 // Calculate space needed to print bucket range numbers. Leave room to print
407 // nearly the largest bucket range without sliding over the histogram.
408 size_t largest_non_empty_bucket = bucket_count() - 1;
409 while (0 == snapshot->GetCountAtIndex(largest_non_empty_bucket)) {
410 if (0 == largest_non_empty_bucket)
411 break; // All buckets are empty.
412 --largest_non_empty_bucket;
415 // Calculate largest print width needed for any of our bucket range displays.
416 size_t print_width = 1;
417 for (size_t i = 0; i < bucket_count(); ++i) {
418 if (snapshot->GetCountAtIndex(i)) {
419 size_t width = GetAsciiBucketRange(i).size() + 1;
420 if (width > print_width)
421 print_width = width;
425 int64 remaining = sample_count;
426 int64 past = 0;
427 // Output the actual histogram graph.
428 for (size_t i = 0; i < bucket_count(); ++i) {
429 Count current = snapshot->GetCountAtIndex(i);
430 if (!current && !PrintEmptyBucket(i))
431 continue;
432 remaining -= current;
433 std::string range = GetAsciiBucketRange(i);
434 output->append(range);
435 for (size_t j = 0; range.size() + j < print_width + 1; ++j)
436 output->push_back(' ');
437 if (0 == current && i < bucket_count() - 1 &&
438 0 == snapshot->GetCountAtIndex(i + 1)) {
439 while (i < bucket_count() - 1 &&
440 0 == snapshot->GetCountAtIndex(i + 1)) {
441 ++i;
443 output->append("... ");
444 output->append(newline);
445 continue; // No reason to plot emptiness.
447 double current_size = GetBucketSize(current, i);
448 if (graph_it)
449 WriteAsciiBucketGraph(current_size, max_size, output);
450 WriteAsciiBucketContext(past, current, remaining, i, output);
451 output->append(newline);
452 past += current;
454 DCHECK_EQ(sample_count, past);
457 double Histogram::GetPeakBucketSize(const SampleVector& samples) const {
458 double max = 0;
459 for (size_t i = 0; i < bucket_count() ; ++i) {
460 double current_size = GetBucketSize(samples.GetCountAtIndex(i), i);
461 if (current_size > max)
462 max = current_size;
464 return max;
467 void Histogram::WriteAsciiHeader(const SampleVector& samples,
468 Count sample_count,
469 std::string* output) const {
470 StringAppendF(output,
471 "Histogram: %s recorded %d samples",
472 histogram_name().c_str(),
473 sample_count);
474 if (0 == sample_count) {
475 DCHECK_EQ(samples.sum(), 0);
476 } else {
477 double average = static_cast<float>(samples.sum()) / sample_count;
479 StringAppendF(output, ", average = %.1f", average);
481 if (flags() & ~kHexRangePrintingFlag)
482 StringAppendF(output, " (flags = 0x%x)", flags() & ~kHexRangePrintingFlag);
485 void Histogram::WriteAsciiBucketContext(const int64 past,
486 const Count current,
487 const int64 remaining,
488 const size_t i,
489 std::string* output) const {
490 double scaled_sum = (past + current + remaining) / 100.0;
491 WriteAsciiBucketValue(current, scaled_sum, output);
492 if (0 < i) {
493 double percentage = past / scaled_sum;
494 StringAppendF(output, " {%3.1f%%}", percentage);
498 void Histogram::GetParameters(DictionaryValue* params) const {
499 params->SetString("type", HistogramTypeToString(GetHistogramType()));
500 params->SetInteger("min", declared_min());
501 params->SetInteger("max", declared_max());
502 params->SetInteger("bucket_count", static_cast<int>(bucket_count()));
505 void Histogram::GetCountAndBucketData(Count* count,
506 int64* sum,
507 ListValue* buckets) const {
508 scoped_ptr<SampleVector> snapshot = SnapshotSampleVector();
509 *count = snapshot->TotalCount();
510 *sum = snapshot->sum();
511 size_t index = 0;
512 for (size_t i = 0; i < bucket_count(); ++i) {
513 Sample count_at_index = snapshot->GetCountAtIndex(i);
514 if (count_at_index > 0) {
515 scoped_ptr<DictionaryValue> bucket_value(new DictionaryValue());
516 bucket_value->SetInteger("low", ranges(i));
517 if (i != bucket_count() - 1)
518 bucket_value->SetInteger("high", ranges(i + 1));
519 bucket_value->SetInteger("count", count_at_index);
520 buckets->Set(index, bucket_value.release());
521 ++index;
526 //------------------------------------------------------------------------------
527 // LinearHistogram: This histogram uses a traditional set of evenly spaced
528 // buckets.
529 //------------------------------------------------------------------------------
531 LinearHistogram::~LinearHistogram() {}
533 HistogramBase* LinearHistogram::FactoryGet(const std::string& name,
534 Sample minimum,
535 Sample maximum,
536 size_t bucket_count,
537 int32 flags) {
538 return FactoryGetWithRangeDescription(
539 name, minimum, maximum, bucket_count, flags, NULL);
542 HistogramBase* LinearHistogram::FactoryTimeGet(const std::string& name,
543 TimeDelta minimum,
544 TimeDelta maximum,
545 size_t bucket_count,
546 int32 flags) {
547 return FactoryGet(name, static_cast<Sample>(minimum.InMilliseconds()),
548 static_cast<Sample>(maximum.InMilliseconds()), bucket_count,
549 flags);
552 HistogramBase* LinearHistogram::FactoryGet(const char* name,
553 Sample minimum,
554 Sample maximum,
555 size_t bucket_count,
556 int32 flags) {
557 return FactoryGet(std::string(name), minimum, maximum, bucket_count, flags);
560 HistogramBase* LinearHistogram::FactoryTimeGet(const char* name,
561 TimeDelta minimum,
562 TimeDelta maximum,
563 size_t bucket_count,
564 int32 flags) {
565 return FactoryTimeGet(std::string(name), minimum, maximum, bucket_count,
566 flags);
569 HistogramBase* LinearHistogram::FactoryGetWithRangeDescription(
570 const std::string& name,
571 Sample minimum,
572 Sample maximum,
573 size_t bucket_count,
574 int32 flags,
575 const DescriptionPair descriptions[]) {
576 bool valid_arguments = Histogram::InspectConstructionArguments(
577 name, &minimum, &maximum, &bucket_count);
578 DCHECK(valid_arguments);
580 HistogramBase* histogram = StatisticsRecorder::FindHistogram(name);
581 if (!histogram) {
582 // To avoid racy destruction at shutdown, the following will be leaked.
583 BucketRanges* ranges = new BucketRanges(bucket_count + 1);
584 InitializeBucketRanges(minimum, maximum, ranges);
585 const BucketRanges* registered_ranges =
586 StatisticsRecorder::RegisterOrDeleteDuplicateRanges(ranges);
588 LinearHistogram* tentative_histogram =
589 new LinearHistogram(name, minimum, maximum, registered_ranges);
591 // Set range descriptions.
592 if (descriptions) {
593 for (int i = 0; descriptions[i].description; ++i) {
594 tentative_histogram->bucket_description_[descriptions[i].sample] =
595 descriptions[i].description;
599 tentative_histogram->SetFlags(flags);
600 histogram =
601 StatisticsRecorder::RegisterOrDeleteDuplicate(tentative_histogram);
604 DCHECK_EQ(LINEAR_HISTOGRAM, histogram->GetHistogramType());
605 if (!histogram->HasConstructionArguments(minimum, maximum, bucket_count)) {
606 // The construction arguments do not match the existing histogram. This can
607 // come about if an extension updates in the middle of a chrome run and has
608 // changed one of them, or simply by bad code within Chrome itself. We
609 // return NULL here with the expectation that bad code in Chrome will crash
610 // on dereference, but extension/Pepper APIs will guard against NULL and not
611 // crash.
612 DLOG(ERROR) << "Histogram " << name << " has bad construction arguments";
613 return NULL;
615 return histogram;
618 HistogramType LinearHistogram::GetHistogramType() const {
619 return LINEAR_HISTOGRAM;
622 LinearHistogram::LinearHistogram(const std::string& name,
623 Sample minimum,
624 Sample maximum,
625 const BucketRanges* ranges)
626 : Histogram(name, minimum, maximum, ranges) {
629 double LinearHistogram::GetBucketSize(Count current, size_t i) const {
630 DCHECK_GT(ranges(i + 1), ranges(i));
631 // Adjacent buckets with different widths would have "surprisingly" many (few)
632 // samples in a histogram if we didn't normalize this way.
633 double denominator = ranges(i + 1) - ranges(i);
634 return current/denominator;
637 const std::string LinearHistogram::GetAsciiBucketRange(size_t i) const {
638 int range = ranges(i);
639 BucketDescriptionMap::const_iterator it = bucket_description_.find(range);
640 if (it == bucket_description_.end())
641 return Histogram::GetAsciiBucketRange(i);
642 return it->second;
645 bool LinearHistogram::PrintEmptyBucket(size_t index) const {
646 return bucket_description_.find(ranges(index)) == bucket_description_.end();
649 // static
650 void LinearHistogram::InitializeBucketRanges(Sample minimum,
651 Sample maximum,
652 BucketRanges* ranges) {
653 double min = minimum;
654 double max = maximum;
655 size_t bucket_count = ranges->bucket_count();
656 for (size_t i = 1; i < bucket_count; ++i) {
657 double linear_range =
658 (min * (bucket_count - 1 - i) + max * (i - 1)) / (bucket_count - 2);
659 ranges->set_range(i, static_cast<Sample>(linear_range + 0.5));
661 ranges->set_range(ranges->bucket_count(), HistogramBase::kSampleType_MAX);
662 ranges->ResetChecksum();
665 // static
666 HistogramBase* LinearHistogram::DeserializeInfoImpl(PickleIterator* iter) {
667 std::string histogram_name;
668 int flags;
669 int declared_min;
670 int declared_max;
671 size_t bucket_count;
672 uint32 range_checksum;
674 if (!ReadHistogramArguments(iter, &histogram_name, &flags, &declared_min,
675 &declared_max, &bucket_count, &range_checksum)) {
676 return NULL;
679 HistogramBase* histogram = LinearHistogram::FactoryGet(
680 histogram_name, declared_min, declared_max, bucket_count, flags);
681 if (!ValidateRangeChecksum(*histogram, range_checksum)) {
682 // The serialized histogram might be corrupted.
683 return NULL;
685 return histogram;
688 //------------------------------------------------------------------------------
689 // This section provides implementation for BooleanHistogram.
690 //------------------------------------------------------------------------------
692 HistogramBase* BooleanHistogram::FactoryGet(const std::string& name,
693 int32 flags) {
694 HistogramBase* histogram = StatisticsRecorder::FindHistogram(name);
695 if (!histogram) {
696 // To avoid racy destruction at shutdown, the following will be leaked.
697 BucketRanges* ranges = new BucketRanges(4);
698 LinearHistogram::InitializeBucketRanges(1, 2, ranges);
699 const BucketRanges* registered_ranges =
700 StatisticsRecorder::RegisterOrDeleteDuplicateRanges(ranges);
702 BooleanHistogram* tentative_histogram =
703 new BooleanHistogram(name, registered_ranges);
705 tentative_histogram->SetFlags(flags);
706 histogram =
707 StatisticsRecorder::RegisterOrDeleteDuplicate(tentative_histogram);
710 DCHECK_EQ(BOOLEAN_HISTOGRAM, histogram->GetHistogramType());
711 return histogram;
714 HistogramBase* BooleanHistogram::FactoryGet(const char* name, int32 flags) {
715 return FactoryGet(std::string(name), flags);
718 HistogramType BooleanHistogram::GetHistogramType() const {
719 return BOOLEAN_HISTOGRAM;
722 BooleanHistogram::BooleanHistogram(const std::string& name,
723 const BucketRanges* ranges)
724 : LinearHistogram(name, 1, 2, ranges) {}
726 HistogramBase* BooleanHistogram::DeserializeInfoImpl(PickleIterator* iter) {
727 std::string histogram_name;
728 int flags;
729 int declared_min;
730 int declared_max;
731 size_t bucket_count;
732 uint32 range_checksum;
734 if (!ReadHistogramArguments(iter, &histogram_name, &flags, &declared_min,
735 &declared_max, &bucket_count, &range_checksum)) {
736 return NULL;
739 HistogramBase* histogram = BooleanHistogram::FactoryGet(
740 histogram_name, flags);
741 if (!ValidateRangeChecksum(*histogram, range_checksum)) {
742 // The serialized histogram might be corrupted.
743 return NULL;
745 return histogram;
748 //------------------------------------------------------------------------------
749 // CustomHistogram:
750 //------------------------------------------------------------------------------
752 HistogramBase* CustomHistogram::FactoryGet(
753 const std::string& name,
754 const std::vector<Sample>& custom_ranges,
755 int32 flags) {
756 CHECK(ValidateCustomRanges(custom_ranges));
758 HistogramBase* histogram = StatisticsRecorder::FindHistogram(name);
759 if (!histogram) {
760 BucketRanges* ranges = CreateBucketRangesFromCustomRanges(custom_ranges);
761 const BucketRanges* registered_ranges =
762 StatisticsRecorder::RegisterOrDeleteDuplicateRanges(ranges);
764 // To avoid racy destruction at shutdown, the following will be leaked.
765 CustomHistogram* tentative_histogram =
766 new CustomHistogram(name, registered_ranges);
768 tentative_histogram->SetFlags(flags);
770 histogram =
771 StatisticsRecorder::RegisterOrDeleteDuplicate(tentative_histogram);
774 DCHECK_EQ(histogram->GetHistogramType(), CUSTOM_HISTOGRAM);
775 return histogram;
778 HistogramBase* CustomHistogram::FactoryGet(
779 const char* name,
780 const std::vector<Sample>& custom_ranges,
781 int32 flags) {
782 return FactoryGet(std::string(name), custom_ranges, flags);
785 HistogramType CustomHistogram::GetHistogramType() const {
786 return CUSTOM_HISTOGRAM;
789 // static
790 std::vector<Sample> CustomHistogram::ArrayToCustomRanges(
791 const Sample* values, size_t num_values) {
792 std::vector<Sample> all_values;
793 for (size_t i = 0; i < num_values; ++i) {
794 Sample value = values[i];
795 all_values.push_back(value);
797 // Ensure that a guard bucket is added. If we end up with duplicate
798 // values, FactoryGet will take care of removing them.
799 all_values.push_back(value + 1);
801 return all_values;
804 CustomHistogram::CustomHistogram(const std::string& name,
805 const BucketRanges* ranges)
806 : Histogram(name,
807 ranges->range(1),
808 ranges->range(ranges->bucket_count() - 1),
809 ranges) {}
811 bool CustomHistogram::SerializeInfoImpl(Pickle* pickle) const {
812 if (!Histogram::SerializeInfoImpl(pickle))
813 return false;
815 // Serialize ranges. First and last ranges are alwasy 0 and INT_MAX, so don't
816 // write them.
817 for (size_t i = 1; i < bucket_ranges()->bucket_count(); ++i) {
818 if (!pickle->WriteInt(bucket_ranges()->range(i)))
819 return false;
821 return true;
824 double CustomHistogram::GetBucketSize(Count current, size_t i) const {
825 return 1;
828 // static
829 HistogramBase* CustomHistogram::DeserializeInfoImpl(PickleIterator* iter) {
830 std::string histogram_name;
831 int flags;
832 int declared_min;
833 int declared_max;
834 size_t bucket_count;
835 uint32 range_checksum;
837 if (!ReadHistogramArguments(iter, &histogram_name, &flags, &declared_min,
838 &declared_max, &bucket_count, &range_checksum)) {
839 return NULL;
842 // First and last ranges are not serialized.
843 std::vector<Sample> sample_ranges(bucket_count - 1);
845 for (size_t i = 0; i < sample_ranges.size(); ++i) {
846 if (!iter->ReadInt(&sample_ranges[i]))
847 return NULL;
850 HistogramBase* histogram = CustomHistogram::FactoryGet(
851 histogram_name, sample_ranges, flags);
852 if (!ValidateRangeChecksum(*histogram, range_checksum)) {
853 // The serialized histogram might be corrupted.
854 return NULL;
856 return histogram;
859 // static
860 bool CustomHistogram::ValidateCustomRanges(
861 const std::vector<Sample>& custom_ranges) {
862 bool has_valid_range = false;
863 for (size_t i = 0; i < custom_ranges.size(); i++) {
864 Sample sample = custom_ranges[i];
865 if (sample < 0 || sample > HistogramBase::kSampleType_MAX - 1)
866 return false;
867 if (sample != 0)
868 has_valid_range = true;
870 return has_valid_range;
873 // static
874 BucketRanges* CustomHistogram::CreateBucketRangesFromCustomRanges(
875 const std::vector<Sample>& custom_ranges) {
876 // Remove the duplicates in the custom ranges array.
877 std::vector<int> ranges = custom_ranges;
878 ranges.push_back(0); // Ensure we have a zero value.
879 ranges.push_back(HistogramBase::kSampleType_MAX);
880 std::sort(ranges.begin(), ranges.end());
881 ranges.erase(std::unique(ranges.begin(), ranges.end()), ranges.end());
883 BucketRanges* bucket_ranges = new BucketRanges(ranges.size());
884 for (size_t i = 0; i < ranges.size(); i++) {
885 bucket_ranges->set_range(i, ranges[i]);
887 bucket_ranges->ResetChecksum();
888 return bucket_ranges;
891 } // namespace base