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"
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"
33 bool ReadHistogramArguments(PickleIterator
* iter
,
34 std::string
* histogram_name
,
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
;
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 ||
54 *declared_max
< *declared_min
||
55 INT_MAX
/ sizeof(HistogramBase::Count
) <= *bucket_count
||
57 DLOG(ERROR
) << "Values error decoding Histogram: " << histogram_name
;
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
;
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
;
79 typedef HistogramBase::Count Count
;
80 typedef HistogramBase::Sample Sample
;
83 const size_t Histogram::kBucketCount_MAX
= 16384u;
85 HistogramBase
* Histogram::FactoryGet(const std::string
& name
,
90 bool valid_arguments
=
91 InspectConstructionArguments(name
, &minimum
, &maximum
, &bucket_count
);
92 DCHECK(valid_arguments
);
94 HistogramBase
* histogram
= StatisticsRecorder::FindHistogram(name
);
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
);
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
118 DLOG(ERROR
) << "Histogram " << name
<< " has bad construction arguments";
124 HistogramBase
* Histogram::FactoryTimeGet(const std::string
& name
,
129 return FactoryGet(name
, static_cast<Sample
>(minimum
.InMilliseconds()),
130 static_cast<Sample
>(maximum
.InMilliseconds()), bucket_count
,
134 HistogramBase
* Histogram::FactoryGet(const char* name
,
139 return FactoryGet(std::string(name
), minimum
, maximum
, bucket_count
, flags
);
142 HistogramBase
* Histogram::FactoryTimeGet(const char* name
,
147 return FactoryTimeGet(std::string(name
), minimum
, maximum
, bucket_count
,
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.
161 void Histogram::InitializeBucketRanges(Sample minimum
,
163 BucketRanges
* ranges
) {
164 double log_max
= log(static_cast<double>(maximum
));
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
) {
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
;
179 next
= static_cast<int>(floor(exp(log_next
) + 0.5));
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();
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();
208 int delta
= static_cast<int>(delta64
);
209 if (delta
!= delta64
)
210 delta
= INT_MAX
; // Flag all giant errors as INT_MAX.
212 UMA_HISTOGRAM_COUNTS("Histogram.InconsistentCountHigh", delta
);
213 if (delta
> kCommonRaceBasedCountMismatch
)
214 inconsistencies
|= COUNT_HIGH_ERROR
;
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();
234 bool Histogram::InspectConstructionArguments(const std::string
& name
,
237 size_t* bucket_count
) {
238 // Defensive code for backward compatibility.
240 DVLOG(1) << "Histogram: " << name
<< " has bad minimum: " << *minimum
;
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: "
250 *bucket_count
= kBucketCount_MAX
- 1;
253 if (*minimum
>= *maximum
)
255 if (*bucket_count
< 3)
257 if (*bucket_count
> static_cast<size_t>(*maximum
- *minimum
+ 2))
262 HistogramType
Histogram::GetHistogramType() const {
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;
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
,
322 const BucketRanges
* ranges
)
323 : HistogramBase(name
),
324 bucket_ranges_(ranges
),
325 declared_min_(minimum
),
326 declared_max_(maximum
) {
328 samples_
.reset(new SampleVector(ranges
));
331 Histogram::~Histogram() {
334 bool Histogram::PrintEmptyBucket(size_t index
) const {
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 //------------------------------------------------------------------------------
360 HistogramBase
* Histogram::DeserializeInfoImpl(PickleIterator
* iter
) {
361 std::string histogram_name
;
366 uint32 range_checksum
;
368 if (!ReadHistogramArguments(iter
, &histogram_name
, &flags
, &declared_min
,
369 &declared_max
, &bucket_count
, &range_checksum
)) {
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.
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.
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
)
425 int64 remaining
= sample_count
;
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
))
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)) {
443 output
->append("... ");
444 output
->append(newline
);
445 continue; // No reason to plot emptiness.
447 double current_size
= GetBucketSize(current
, i
);
449 WriteAsciiBucketGraph(current_size
, max_size
, output
);
450 WriteAsciiBucketContext(past
, current
, remaining
, i
, output
);
451 output
->append(newline
);
454 DCHECK_EQ(sample_count
, past
);
457 double Histogram::GetPeakBucketSize(const SampleVector
& samples
) const {
459 for (size_t i
= 0; i
< bucket_count() ; ++i
) {
460 double current_size
= GetBucketSize(samples
.GetCountAtIndex(i
), i
);
461 if (current_size
> max
)
467 void Histogram::WriteAsciiHeader(const SampleVector
& samples
,
469 std::string
* output
) const {
470 StringAppendF(output
,
471 "Histogram: %s recorded %d samples",
472 histogram_name().c_str(),
474 if (0 == sample_count
) {
475 DCHECK_EQ(samples
.sum(), 0);
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
,
487 const int64 remaining
,
489 std::string
* output
) const {
490 double scaled_sum
= (past
+ current
+ remaining
) / 100.0;
491 WriteAsciiBucketValue(current
, scaled_sum
, output
);
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
,
507 ListValue
* buckets
) const {
508 scoped_ptr
<SampleVector
> snapshot
= SnapshotSampleVector();
509 *count
= snapshot
->TotalCount();
510 *sum
= snapshot
->sum();
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());
526 //------------------------------------------------------------------------------
527 // LinearHistogram: This histogram uses a traditional set of evenly spaced
529 //------------------------------------------------------------------------------
531 LinearHistogram::~LinearHistogram() {}
533 HistogramBase
* LinearHistogram::FactoryGet(const std::string
& name
,
538 return FactoryGetWithRangeDescription(
539 name
, minimum
, maximum
, bucket_count
, flags
, NULL
);
542 HistogramBase
* LinearHistogram::FactoryTimeGet(const std::string
& name
,
547 return FactoryGet(name
, static_cast<Sample
>(minimum
.InMilliseconds()),
548 static_cast<Sample
>(maximum
.InMilliseconds()), bucket_count
,
552 HistogramBase
* LinearHistogram::FactoryGet(const char* name
,
557 return FactoryGet(std::string(name
), minimum
, maximum
, bucket_count
, flags
);
560 HistogramBase
* LinearHistogram::FactoryTimeGet(const char* name
,
565 return FactoryTimeGet(std::string(name
), minimum
, maximum
, bucket_count
,
569 HistogramBase
* LinearHistogram::FactoryGetWithRangeDescription(
570 const std::string
& name
,
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
);
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.
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
);
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
612 DLOG(ERROR
) << "Histogram " << name
<< " has bad construction arguments";
618 HistogramType
LinearHistogram::GetHistogramType() const {
619 return LINEAR_HISTOGRAM
;
622 LinearHistogram::LinearHistogram(const std::string
& name
,
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
);
645 bool LinearHistogram::PrintEmptyBucket(size_t index
) const {
646 return bucket_description_
.find(ranges(index
)) == bucket_description_
.end();
650 void LinearHistogram::InitializeBucketRanges(Sample minimum
,
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();
666 HistogramBase
* LinearHistogram::DeserializeInfoImpl(PickleIterator
* iter
) {
667 std::string histogram_name
;
672 uint32 range_checksum
;
674 if (!ReadHistogramArguments(iter
, &histogram_name
, &flags
, &declared_min
,
675 &declared_max
, &bucket_count
, &range_checksum
)) {
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.
688 //------------------------------------------------------------------------------
689 // This section provides implementation for BooleanHistogram.
690 //------------------------------------------------------------------------------
692 HistogramBase
* BooleanHistogram::FactoryGet(const std::string
& name
,
694 HistogramBase
* histogram
= StatisticsRecorder::FindHistogram(name
);
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
);
707 StatisticsRecorder::RegisterOrDeleteDuplicate(tentative_histogram
);
710 DCHECK_EQ(BOOLEAN_HISTOGRAM
, histogram
->GetHistogramType());
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
;
732 uint32 range_checksum
;
734 if (!ReadHistogramArguments(iter
, &histogram_name
, &flags
, &declared_min
,
735 &declared_max
, &bucket_count
, &range_checksum
)) {
739 HistogramBase
* histogram
= BooleanHistogram::FactoryGet(
740 histogram_name
, flags
);
741 if (!ValidateRangeChecksum(*histogram
, range_checksum
)) {
742 // The serialized histogram might be corrupted.
748 //------------------------------------------------------------------------------
750 //------------------------------------------------------------------------------
752 HistogramBase
* CustomHistogram::FactoryGet(
753 const std::string
& name
,
754 const std::vector
<Sample
>& custom_ranges
,
756 CHECK(ValidateCustomRanges(custom_ranges
));
758 HistogramBase
* histogram
= StatisticsRecorder::FindHistogram(name
);
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
);
771 StatisticsRecorder::RegisterOrDeleteDuplicate(tentative_histogram
);
774 DCHECK_EQ(histogram
->GetHistogramType(), CUSTOM_HISTOGRAM
);
778 HistogramBase
* CustomHistogram::FactoryGet(
780 const std::vector
<Sample
>& custom_ranges
,
782 return FactoryGet(std::string(name
), custom_ranges
, flags
);
785 HistogramType
CustomHistogram::GetHistogramType() const {
786 return CUSTOM_HISTOGRAM
;
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);
804 CustomHistogram::CustomHistogram(const std::string
& name
,
805 const BucketRanges
* ranges
)
808 ranges
->range(ranges
->bucket_count() - 1),
811 bool CustomHistogram::SerializeInfoImpl(Pickle
* pickle
) const {
812 if (!Histogram::SerializeInfoImpl(pickle
))
815 // Serialize ranges. First and last ranges are alwasy 0 and INT_MAX, so don't
817 for (size_t i
= 1; i
< bucket_ranges()->bucket_count(); ++i
) {
818 if (!pickle
->WriteInt(bucket_ranges()->range(i
)))
824 double CustomHistogram::GetBucketSize(Count current
, size_t i
) const {
829 HistogramBase
* CustomHistogram::DeserializeInfoImpl(PickleIterator
* iter
) {
830 std::string histogram_name
;
835 uint32 range_checksum
;
837 if (!ReadHistogramArguments(iter
, &histogram_name
, &flags
, &declared_min
,
838 &declared_max
, &bucket_count
, &range_checksum
)) {
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
]))
850 HistogramBase
* histogram
= CustomHistogram::FactoryGet(
851 histogram_name
, sample_ranges
, flags
);
852 if (!ValidateRangeChecksum(*histogram
, range_checksum
)) {
853 // The serialized histogram might be corrupted.
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)
868 has_valid_range
= true;
870 return has_valid_range
;
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
;