blob: 1f268295e24675df793195b692bfddb106d2902e [file] [log] [blame]
[email protected]a93721e22012-01-06 02:13:281// Copyright (c) 2012 The Chromium Authors. All rights reserved.
license.botbf09a502008-08-24 00:55:552// Use of this source code is governed by a BSD-style license that can be
3// found in the LICENSE file.
initial.commitd7cae122008-07-26 21:49:384
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.
9
[email protected]835d7c82010-10-14 04:38:3810#include "base/metrics/histogram.h"
initial.commitd7cae122008-07-26 21:49:3811
12#include <math.h>
[email protected]f1633932010-08-17 23:05:2813
14#include <algorithm>
initial.commitd7cae122008-07-26 21:49:3815#include <string>
16
[email protected]ec0c0aa2012-08-14 02:02:0017#include "base/compiler_specific.h"
18#include "base/debug/alias.h"
initial.commitd7cae122008-07-26 21:49:3819#include "base/logging.h"
[email protected]877ef562012-10-20 02:56:1820#include "base/metrics/sample_vector.h"
[email protected]567d30e2012-07-13 21:48:2921#include "base/metrics/statistics_recorder.h"
[email protected]3f383852009-04-03 18:18:5522#include "base/pickle.h"
[email protected]ec0c0aa2012-08-14 02:02:0023#include "base/string_util.h"
[email protected]f1633932010-08-17 23:05:2824#include "base/stringprintf.h"
[email protected]bc581a682011-01-01 23:16:2025#include "base/synchronization/lock.h"
[email protected]24a7ec52012-10-08 10:31:5026#include "base/values.h"
initial.commitd7cae122008-07-26 21:49:3827
[email protected]34d062322012-08-01 21:34:0828using std::string;
29using std::vector;
30
[email protected]835d7c82010-10-14 04:38:3831namespace base {
[email protected]e1acf6f2008-10-27 20:43:3332
[email protected]c50c21d2013-01-11 21:52:4433namespace {
34
35bool ReadHistogramArguments(PickleIterator* iter,
36 string* histogram_name,
37 int* flags,
38 int* declared_min,
39 int* declared_max,
40 uint64* bucket_count,
41 uint32* range_checksum) {
42 if (!iter->ReadString(histogram_name) ||
43 !iter->ReadInt(flags) ||
44 !iter->ReadInt(declared_min) ||
45 !iter->ReadInt(declared_max) ||
46 !iter->ReadUInt64(bucket_count) ||
47 !iter->ReadUInt32(range_checksum)) {
48 DLOG(ERROR) << "Pickle error decoding Histogram: " << *histogram_name;
49 return false;
50 }
51
52 // Since these fields may have come from an untrusted renderer, do additional
53 // checks above and beyond those in Histogram::Initialize()
54 if (*declared_max <= 0 ||
55 *declared_min <= 0 ||
56 *declared_max < *declared_min ||
57 INT_MAX / sizeof(HistogramBase::Count) <= *bucket_count ||
58 *bucket_count < 2) {
59 DLOG(ERROR) << "Values error decoding Histogram: " << histogram_name;
60 return false;
61 }
62
63 // We use the arguments to find or create the local version of the histogram
64 // in this process, so we need to clear the IPC flag.
65 DCHECK(*flags & HistogramBase::kIPCSerializationSourceFlag);
66 *flags &= ~HistogramBase::kIPCSerializationSourceFlag;
67
68 return true;
69}
70
71bool ValidateRangeChecksum(const HistogramBase& histogram,
72 uint32 range_checksum) {
73 const Histogram& casted_histogram =
74 static_cast<const Histogram&>(histogram);
75
76 return casted_histogram.bucket_ranges()->checksum() == range_checksum;
77}
78
79} // namespace
80
[email protected]34d062322012-08-01 21:34:0881typedef HistogramBase::Count Count;
82typedef HistogramBase::Sample Sample;
initial.commitd7cae122008-07-26 21:49:3883
[email protected]b122c0c2011-02-23 22:31:1884// static
[email protected]9fce5f02011-03-02 08:04:5785const size_t Histogram::kBucketCount_MAX = 16384u;
[email protected]b122c0c2011-02-23 22:31:1886
[email protected]de415552013-01-23 04:12:1787HistogramBase* Histogram::FactoryGet(const string& name,
88 Sample minimum,
89 Sample maximum,
90 size_t bucket_count,
91 int32 flags) {
[email protected]e184be902012-08-07 04:49:2492 bool valid_arguments =
93 InspectConstructionArguments(name, &minimum, &maximum, &bucket_count);
94 DCHECK(valid_arguments);
[email protected]a93721e22012-01-06 02:13:2895
[email protected]cc7dec212013-03-01 03:53:2596 HistogramBase* histogram = StatisticsRecorder::FindHistogram(name);
[email protected]993ae742012-07-18 18:06:3097 if (!histogram) {
[email protected]81ce9f3b2011-04-05 04:48:5398 // To avoid racy destruction at shutdown, the following will be leaked.
[email protected]34d062322012-08-01 21:34:0899 BucketRanges* ranges = new BucketRanges(bucket_count + 1);
100 InitializeBucketRanges(minimum, maximum, bucket_count, ranges);
101 const BucketRanges* registered_ranges =
102 StatisticsRecorder::RegisterOrDeleteDuplicateRanges(ranges);
103
104 Histogram* tentative_histogram =
105 new Histogram(name, minimum, maximum, bucket_count, registered_ranges);
[email protected]263a17a2012-08-16 03:03:54106
[email protected]81ce9f3b2011-04-05 04:48:53107 tentative_histogram->SetFlags(flags);
108 histogram =
109 StatisticsRecorder::RegisterOrDeleteDuplicate(tentative_histogram);
[email protected]e8829a192009-12-06 00:09:37110 }
111
[email protected]cc7dec212013-03-01 03:53:25112 DCHECK_EQ(HISTOGRAM, histogram->GetHistogramType());
[email protected]065d1702012-08-23 23:55:13113 CHECK(histogram->HasConstructionArguments(minimum, maximum, bucket_count));
[email protected]e8829a192009-12-06 00:09:37114 return histogram;
115}
116
[email protected]de415552013-01-23 04:12:17117HistogramBase* Histogram::FactoryTimeGet(const string& name,
118 TimeDelta minimum,
119 TimeDelta maximum,
120 size_t bucket_count,
121 int32 flags) {
[email protected]34d062322012-08-01 21:34:08122 return FactoryGet(name, minimum.InMilliseconds(), maximum.InMilliseconds(),
123 bucket_count, flags);
124}
125
126TimeTicks Histogram::DebugNow() {
127#ifndef NDEBUG
128 return TimeTicks::Now();
129#else
130 return TimeTicks();
131#endif
132}
133
134// Calculate what range of values are held in each bucket.
135// We have to be careful that we don't pick a ratio between starting points in
136// consecutive buckets that is sooo small, that the integer bounds are the same
137// (effectively making one bucket get no values). We need to avoid:
138// ranges(i) == ranges(i + 1)
139// To avoid that, we just do a fine-grained bucket width as far as we need to
140// until we get a ratio that moves us along at least 2 units at a time. From
141// that bucket onward we do use the exponential growth of buckets.
142//
143// static
144void Histogram::InitializeBucketRanges(Sample minimum,
145 Sample maximum,
146 size_t bucket_count,
147 BucketRanges* ranges) {
148 DCHECK_EQ(ranges->size(), bucket_count + 1);
149 double log_max = log(static_cast<double>(maximum));
150 double log_ratio;
151 double log_next;
152 size_t bucket_index = 1;
153 Sample current = minimum;
154 ranges->set_range(bucket_index, current);
155 while (bucket_count > ++bucket_index) {
156 double log_current;
157 log_current = log(static_cast<double>(current));
158 // Calculate the count'th root of the range.
159 log_ratio = (log_max - log_current) / (bucket_count - bucket_index);
160 // See where the next bucket would start.
161 log_next = log_current + log_ratio;
162 Sample next;
163 next = static_cast<int>(floor(exp(log_next) + 0.5));
164 if (next > current)
165 current = next;
166 else
167 ++current; // Just do a narrow bucket, and keep trying.
168 ranges->set_range(bucket_index, current);
169 }
170 ranges->set_range(ranges->size() - 1, HistogramBase::kSampleType_MAX);
171 ranges->ResetChecksum();
172}
173
[email protected]2f7d9cd2012-09-22 03:42:12174// static
175const int Histogram::kCommonRaceBasedCountMismatch = 5;
[email protected]34d062322012-08-01 21:34:08176
[email protected]cc7dec212013-03-01 03:53:25177int Histogram::FindCorruption(const HistogramSamples& samples) const {
[email protected]34d062322012-08-01 21:34:08178 int inconsistencies = NO_INCONSISTENCIES;
179 Sample previous_range = -1; // Bottom range is always 0.
[email protected]34d062322012-08-01 21:34:08180 for (size_t index = 0; index < bucket_count(); ++index) {
[email protected]34d062322012-08-01 21:34:08181 int new_range = ranges(index);
182 if (previous_range >= new_range)
183 inconsistencies |= BUCKET_ORDER_ERROR;
184 previous_range = new_range;
185 }
186
187 if (!bucket_ranges()->HasValidChecksum())
188 inconsistencies |= RANGE_CHECKSUM_ERROR;
189
[email protected]2f7d9cd2012-09-22 03:42:12190 int64 delta64 = samples.redundant_count() - samples.TotalCount();
[email protected]34d062322012-08-01 21:34:08191 if (delta64 != 0) {
192 int delta = static_cast<int>(delta64);
193 if (delta != delta64)
194 delta = INT_MAX; // Flag all giant errors as INT_MAX.
[email protected]34d062322012-08-01 21:34:08195 if (delta > 0) {
196 UMA_HISTOGRAM_COUNTS("Histogram.InconsistentCountHigh", delta);
197 if (delta > kCommonRaceBasedCountMismatch)
198 inconsistencies |= COUNT_HIGH_ERROR;
199 } else {
200 DCHECK_GT(0, delta);
201 UMA_HISTOGRAM_COUNTS("Histogram.InconsistentCountLow", -delta);
202 if (-delta > kCommonRaceBasedCountMismatch)
203 inconsistencies |= COUNT_LOW_ERROR;
204 }
205 }
[email protected]cc7dec212013-03-01 03:53:25206 return inconsistencies;
[email protected]34d062322012-08-01 21:34:08207}
208
[email protected]34d062322012-08-01 21:34:08209Sample Histogram::ranges(size_t i) const {
210 return bucket_ranges_->range(i);
211}
212
213size_t Histogram::bucket_count() const {
214 return bucket_count_;
215}
216
[email protected]34d062322012-08-01 21:34:08217// static
218bool Histogram::InspectConstructionArguments(const string& name,
219 Sample* minimum,
220 Sample* maximum,
221 size_t* bucket_count) {
222 // Defensive code for backward compatibility.
223 if (*minimum < 1) {
[email protected]a5c7bd792012-08-02 00:29:04224 DVLOG(1) << "Histogram: " << name << " has bad minimum: " << *minimum;
[email protected]34d062322012-08-01 21:34:08225 *minimum = 1;
226 }
227 if (*maximum >= kSampleType_MAX) {
[email protected]a5c7bd792012-08-02 00:29:04228 DVLOG(1) << "Histogram: " << name << " has bad maximum: " << *maximum;
229 *maximum = kSampleType_MAX - 1;
[email protected]34d062322012-08-01 21:34:08230 }
[email protected]e184be902012-08-07 04:49:24231 if (*bucket_count >= kBucketCount_MAX) {
232 DVLOG(1) << "Histogram: " << name << " has bad bucket_count: "
233 << *bucket_count;
234 *bucket_count = kBucketCount_MAX - 1;
235 }
[email protected]34d062322012-08-01 21:34:08236
[email protected]e184be902012-08-07 04:49:24237 if (*minimum >= *maximum)
238 return false;
239 if (*bucket_count < 3)
[email protected]34d062322012-08-01 21:34:08240 return false;
241 if (*bucket_count > static_cast<size_t>(*maximum - *minimum + 2))
242 return false;
243 return true;
244}
245
[email protected]07c02402012-10-31 06:20:25246HistogramType Histogram::GetHistogramType() const {
247 return HISTOGRAM;
248}
249
[email protected]abae9b022012-10-24 08:18:52250bool Histogram::HasConstructionArguments(Sample minimum,
251 Sample maximum,
252 size_t bucket_count) const {
253 return ((minimum == declared_min_) && (maximum == declared_max_) &&
254 (bucket_count == bucket_count_));
255}
256
257void Histogram::Add(int value) {
258 DCHECK_EQ(0, ranges(0));
259 DCHECK_EQ(kSampleType_MAX, ranges(bucket_count_));
260
261 if (value > kSampleType_MAX - 1)
262 value = kSampleType_MAX - 1;
263 if (value < 0)
264 value = 0;
265 samples_->Accumulate(value, 1);
266}
267
268scoped_ptr<HistogramSamples> Histogram::SnapshotSamples() const {
269 return SnapshotSampleVector().PassAs<HistogramSamples>();
270}
271
[email protected]c50c21d2013-01-11 21:52:44272void Histogram::AddSamples(const HistogramSamples& samples) {
273 samples_->Add(samples);
274}
275
276bool Histogram::AddSamplesFromPickle(PickleIterator* iter) {
277 return samples_->AddFromPickle(iter);
278}
279
[email protected]abae9b022012-10-24 08:18:52280// The following methods provide a graphical histogram display.
281void Histogram::WriteHTMLGraph(string* output) const {
282 // TBD(jar) Write a nice HTML bar chart, with divs an mouse-overs etc.
283 output->append("<PRE>");
284 WriteAsciiImpl(true, "<br>", output);
285 output->append("</PRE>");
286}
287
288void Histogram::WriteAscii(string* output) const {
289 WriteAsciiImpl(true, "\n", output);
290}
291
[email protected]c50c21d2013-01-11 21:52:44292bool Histogram::SerializeInfoImpl(Pickle* pickle) const {
293 DCHECK(bucket_ranges()->HasValidChecksum());
294 return pickle->WriteString(histogram_name()) &&
295 pickle->WriteInt(flags()) &&
296 pickle->WriteInt(declared_min()) &&
297 pickle->WriteInt(declared_max()) &&
298 pickle->WriteUInt64(bucket_count()) &&
299 pickle->WriteUInt32(bucket_ranges()->checksum());
300}
301
[email protected]abae9b022012-10-24 08:18:52302Histogram::Histogram(const string& name,
303 Sample minimum,
304 Sample maximum,
305 size_t bucket_count,
306 const BucketRanges* ranges)
307 : HistogramBase(name),
308 bucket_ranges_(ranges),
309 declared_min_(minimum),
310 declared_max_(maximum),
311 bucket_count_(bucket_count) {
312 if (ranges)
313 samples_.reset(new SampleVector(ranges));
314}
315
316Histogram::~Histogram() {
317 if (StatisticsRecorder::dump_on_exit()) {
318 string output;
319 WriteAsciiImpl(true, "\n", &output);
320 DLOG(INFO) << output;
321 }
322}
323
[email protected]34d062322012-08-01 21:34:08324bool Histogram::PrintEmptyBucket(size_t index) const {
325 return true;
326}
327
[email protected]34d062322012-08-01 21:34:08328// Use the actual bucket widths (like a linear histogram) until the widths get
329// over some transition value, and then use that transition width. Exponentials
330// get so big so fast (and we don't expect to see a lot of entries in the large
331// buckets), so we need this to make it possible to see what is going on and
332// not have 0-graphical-height buckets.
333double Histogram::GetBucketSize(Count current, size_t i) const {
334 DCHECK_GT(ranges(i + 1), ranges(i));
335 static const double kTransitionWidth = 5;
336 double denominator = ranges(i + 1) - ranges(i);
337 if (denominator > kTransitionWidth)
338 denominator = kTransitionWidth; // Stop trying to normalize.
339 return current/denominator;
340}
341
342const string Histogram::GetAsciiBucketRange(size_t i) const {
343 string result;
[email protected]7c7a42752012-08-09 05:14:15344 if (kHexRangePrintingFlag & flags())
[email protected]34d062322012-08-01 21:34:08345 StringAppendF(&result, "%#x", ranges(i));
346 else
347 StringAppendF(&result, "%d", ranges(i));
348 return result;
349}
350
[email protected]34d062322012-08-01 21:34:08351//------------------------------------------------------------------------------
352// Private methods
353
[email protected]c50c21d2013-01-11 21:52:44354// static
355HistogramBase* Histogram::DeserializeInfoImpl(PickleIterator* iter) {
356 string histogram_name;
357 int flags;
358 int declared_min;
359 int declared_max;
360 uint64 bucket_count;
361 uint32 range_checksum;
362
363 if (!ReadHistogramArguments(iter, &histogram_name, &flags, &declared_min,
364 &declared_max, &bucket_count, &range_checksum)) {
365 return NULL;
366 }
367
368 // Find or create the local version of the histogram in this process.
369 HistogramBase* histogram = Histogram::FactoryGet(
370 histogram_name, declared_min, declared_max, bucket_count, flags);
371
372 if (!ValidateRangeChecksum(*histogram, range_checksum)) {
373 // The serialized histogram might be corrupted.
374 return NULL;
375 }
376 return histogram;
377}
378
[email protected]877ef562012-10-20 02:56:18379scoped_ptr<SampleVector> Histogram::SnapshotSampleVector() const {
380 scoped_ptr<SampleVector> samples(new SampleVector(bucket_ranges()));
381 samples->Add(*samples_);
382 return samples.Pass();
383}
384
[email protected]34d062322012-08-01 21:34:08385void Histogram::WriteAsciiImpl(bool graph_it,
386 const string& newline,
387 string* output) const {
388 // Get local (stack) copies of all effectively volatile class data so that we
389 // are consistent across our output activities.
[email protected]877ef562012-10-20 02:56:18390 scoped_ptr<SampleVector> snapshot = SnapshotSampleVector();
[email protected]2f7d9cd2012-09-22 03:42:12391 Count sample_count = snapshot->TotalCount();
[email protected]34d062322012-08-01 21:34:08392
[email protected]2f7d9cd2012-09-22 03:42:12393 WriteAsciiHeader(*snapshot, sample_count, output);
[email protected]34d062322012-08-01 21:34:08394 output->append(newline);
395
396 // Prepare to normalize graphical rendering of bucket contents.
397 double max_size = 0;
398 if (graph_it)
[email protected]2f7d9cd2012-09-22 03:42:12399 max_size = GetPeakBucketSize(*snapshot);
[email protected]34d062322012-08-01 21:34:08400
401 // Calculate space needed to print bucket range numbers. Leave room to print
402 // nearly the largest bucket range without sliding over the histogram.
403 size_t largest_non_empty_bucket = bucket_count() - 1;
[email protected]2f7d9cd2012-09-22 03:42:12404 while (0 == snapshot->GetCountAtIndex(largest_non_empty_bucket)) {
[email protected]34d062322012-08-01 21:34:08405 if (0 == largest_non_empty_bucket)
406 break; // All buckets are empty.
407 --largest_non_empty_bucket;
408 }
409
410 // Calculate largest print width needed for any of our bucket range displays.
411 size_t print_width = 1;
412 for (size_t i = 0; i < bucket_count(); ++i) {
[email protected]2f7d9cd2012-09-22 03:42:12413 if (snapshot->GetCountAtIndex(i)) {
[email protected]34d062322012-08-01 21:34:08414 size_t width = GetAsciiBucketRange(i).size() + 1;
415 if (width > print_width)
416 print_width = width;
417 }
418 }
419
420 int64 remaining = sample_count;
421 int64 past = 0;
422 // Output the actual histogram graph.
423 for (size_t i = 0; i < bucket_count(); ++i) {
[email protected]2f7d9cd2012-09-22 03:42:12424 Count current = snapshot->GetCountAtIndex(i);
[email protected]34d062322012-08-01 21:34:08425 if (!current && !PrintEmptyBucket(i))
426 continue;
427 remaining -= current;
428 string range = GetAsciiBucketRange(i);
429 output->append(range);
430 for (size_t j = 0; range.size() + j < print_width + 1; ++j)
431 output->push_back(' ');
[email protected]2f7d9cd2012-09-22 03:42:12432 if (0 == current && i < bucket_count() - 1 &&
433 0 == snapshot->GetCountAtIndex(i + 1)) {
434 while (i < bucket_count() - 1 &&
435 0 == snapshot->GetCountAtIndex(i + 1)) {
[email protected]34d062322012-08-01 21:34:08436 ++i;
[email protected]2f7d9cd2012-09-22 03:42:12437 }
[email protected]34d062322012-08-01 21:34:08438 output->append("... ");
439 output->append(newline);
440 continue; // No reason to plot emptiness.
441 }
442 double current_size = GetBucketSize(current, i);
443 if (graph_it)
444 WriteAsciiBucketGraph(current_size, max_size, output);
445 WriteAsciiBucketContext(past, current, remaining, i, output);
446 output->append(newline);
447 past += current;
448 }
449 DCHECK_EQ(sample_count, past);
450}
451
[email protected]2f7d9cd2012-09-22 03:42:12452double Histogram::GetPeakBucketSize(const SampleVector& samples) const {
[email protected]34d062322012-08-01 21:34:08453 double max = 0;
454 for (size_t i = 0; i < bucket_count() ; ++i) {
[email protected]2f7d9cd2012-09-22 03:42:12455 double current_size = GetBucketSize(samples.GetCountAtIndex(i), i);
[email protected]34d062322012-08-01 21:34:08456 if (current_size > max)
457 max = current_size;
458 }
459 return max;
460}
461
[email protected]2f7d9cd2012-09-22 03:42:12462void Histogram::WriteAsciiHeader(const SampleVector& samples,
[email protected]34d062322012-08-01 21:34:08463 Count sample_count,
464 string* output) const {
465 StringAppendF(output,
466 "Histogram: %s recorded %d samples",
467 histogram_name().c_str(),
468 sample_count);
469 if (0 == sample_count) {
[email protected]2f7d9cd2012-09-22 03:42:12470 DCHECK_EQ(samples.sum(), 0);
[email protected]34d062322012-08-01 21:34:08471 } else {
[email protected]2f7d9cd2012-09-22 03:42:12472 double average = static_cast<float>(samples.sum()) / sample_count;
[email protected]34d062322012-08-01 21:34:08473
474 StringAppendF(output, ", average = %.1f", average);
475 }
[email protected]7c7a42752012-08-09 05:14:15476 if (flags() & ~kHexRangePrintingFlag)
477 StringAppendF(output, " (flags = 0x%x)", flags() & ~kHexRangePrintingFlag);
[email protected]34d062322012-08-01 21:34:08478}
479
480void Histogram::WriteAsciiBucketContext(const int64 past,
481 const Count current,
482 const int64 remaining,
483 const size_t i,
484 string* output) const {
485 double scaled_sum = (past + current + remaining) / 100.0;
486 WriteAsciiBucketValue(current, scaled_sum, output);
487 if (0 < i) {
488 double percentage = past / scaled_sum;
489 StringAppendF(output, " {%3.1f%%}", percentage);
490 }
491}
492
493void Histogram::WriteAsciiBucketValue(Count current,
494 double scaled_sum,
495 string* output) const {
496 StringAppendF(output, " (%d = %3.1f%%)", current, current/scaled_sum);
497}
498
499void Histogram::WriteAsciiBucketGraph(double current_size,
500 double max_size,
501 string* output) const {
502 const int k_line_length = 72; // Maximal horizontal width of graph.
503 int x_count = static_cast<int>(k_line_length * (current_size / max_size)
504 + 0.5);
505 int x_remainder = k_line_length - x_count;
506
507 while (0 < x_count--)
508 output->append("-");
509 output->append("O");
510 while (0 < x_remainder--)
511 output->append(" ");
512}
513
[email protected]24a7ec52012-10-08 10:31:50514void Histogram::GetParameters(DictionaryValue* params) const {
[email protected]07c02402012-10-31 06:20:25515 params->SetString("type", HistogramTypeToString(GetHistogramType()));
[email protected]24a7ec52012-10-08 10:31:50516 params->SetInteger("min", declared_min());
517 params->SetInteger("max", declared_max());
518 params->SetInteger("bucket_count", static_cast<int>(bucket_count()));
519}
520
521void Histogram::GetCountAndBucketData(Count* count, ListValue* buckets) const {
[email protected]877ef562012-10-20 02:56:18522 scoped_ptr<SampleVector> snapshot = SnapshotSampleVector();
[email protected]24a7ec52012-10-08 10:31:50523 *count = snapshot->TotalCount();
524 size_t index = 0;
525 for (size_t i = 0; i < bucket_count(); ++i) {
526 Sample count = snapshot->GetCountAtIndex(i);
527 if (count > 0) {
528 scoped_ptr<DictionaryValue> bucket_value(new DictionaryValue());
529 bucket_value->SetInteger("low", ranges(i));
530 if (i != bucket_count() - 1)
531 bucket_value->SetInteger("high", ranges(i + 1));
532 bucket_value->SetInteger("count", count);
533 buckets->Set(index, bucket_value.release());
534 ++index;
535 }
536 }
537}
538
[email protected]34d062322012-08-01 21:34:08539//------------------------------------------------------------------------------
540// LinearHistogram: This histogram uses a traditional set of evenly spaced
541// buckets.
542//------------------------------------------------------------------------------
543
544LinearHistogram::~LinearHistogram() {}
545
[email protected]de415552013-01-23 04:12:17546HistogramBase* LinearHistogram::FactoryGet(const string& name,
547 Sample minimum,
548 Sample maximum,
549 size_t bucket_count,
550 int32 flags) {
[email protected]07c02402012-10-31 06:20:25551 return FactoryGetWithRangeDescription(
552 name, minimum, maximum, bucket_count, flags, NULL);
553}
554
[email protected]de415552013-01-23 04:12:17555HistogramBase* LinearHistogram::FactoryTimeGet(const string& name,
556 TimeDelta minimum,
557 TimeDelta maximum,
558 size_t bucket_count,
559 int32 flags) {
[email protected]07c02402012-10-31 06:20:25560 return FactoryGet(name, minimum.InMilliseconds(), maximum.InMilliseconds(),
561 bucket_count, flags);
562}
563
[email protected]de415552013-01-23 04:12:17564HistogramBase* LinearHistogram::FactoryGetWithRangeDescription(
[email protected]07c02402012-10-31 06:20:25565 const std::string& name,
566 Sample minimum,
567 Sample maximum,
568 size_t bucket_count,
569 int32 flags,
570 const DescriptionPair descriptions[]) {
[email protected]e184be902012-08-07 04:49:24571 bool valid_arguments = Histogram::InspectConstructionArguments(
572 name, &minimum, &maximum, &bucket_count);
573 DCHECK(valid_arguments);
[email protected]34d062322012-08-01 21:34:08574
[email protected]cc7dec212013-03-01 03:53:25575 HistogramBase* histogram = StatisticsRecorder::FindHistogram(name);
[email protected]34d062322012-08-01 21:34:08576 if (!histogram) {
577 // To avoid racy destruction at shutdown, the following will be leaked.
578 BucketRanges* ranges = new BucketRanges(bucket_count + 1);
579 InitializeBucketRanges(minimum, maximum, bucket_count, ranges);
580 const BucketRanges* registered_ranges =
581 StatisticsRecorder::RegisterOrDeleteDuplicateRanges(ranges);
582
583 LinearHistogram* tentative_histogram =
584 new LinearHistogram(name, minimum, maximum, bucket_count,
585 registered_ranges);
[email protected]263a17a2012-08-16 03:03:54586
[email protected]07c02402012-10-31 06:20:25587 // Set range descriptions.
588 if (descriptions) {
589 for (int i = 0; descriptions[i].description; ++i) {
590 tentative_histogram->bucket_description_[descriptions[i].sample] =
591 descriptions[i].description;
592 }
593 }
594
[email protected]34d062322012-08-01 21:34:08595 tentative_histogram->SetFlags(flags);
596 histogram =
597 StatisticsRecorder::RegisterOrDeleteDuplicate(tentative_histogram);
598 }
599
[email protected]cc7dec212013-03-01 03:53:25600 DCHECK_EQ(LINEAR_HISTOGRAM, histogram->GetHistogramType());
[email protected]065d1702012-08-23 23:55:13601 CHECK(histogram->HasConstructionArguments(minimum, maximum, bucket_count));
[email protected]34d062322012-08-01 21:34:08602 return histogram;
603}
604
[email protected]07c02402012-10-31 06:20:25605HistogramType LinearHistogram::GetHistogramType() const {
[email protected]b7d08202011-01-25 17:29:39606 return LINEAR_HISTOGRAM;
607}
608
[email protected]34d062322012-08-01 21:34:08609LinearHistogram::LinearHistogram(const string& name,
[email protected]835d7c82010-10-14 04:38:38610 Sample minimum,
611 Sample maximum,
[email protected]34d062322012-08-01 21:34:08612 size_t bucket_count,
613 const BucketRanges* ranges)
614 : Histogram(name, minimum, maximum, bucket_count, ranges) {
initial.commitd7cae122008-07-26 21:49:38615}
616
initial.commitd7cae122008-07-26 21:49:38617double LinearHistogram::GetBucketSize(Count current, size_t i) const {
[email protected]2ef3748f2010-10-19 17:33:28618 DCHECK_GT(ranges(i + 1), ranges(i));
initial.commitd7cae122008-07-26 21:49:38619 // Adjacent buckets with different widths would have "surprisingly" many (few)
620 // samples in a histogram if we didn't normalize this way.
621 double denominator = ranges(i + 1) - ranges(i);
622 return current/denominator;
623}
624
[email protected]34d062322012-08-01 21:34:08625const string LinearHistogram::GetAsciiBucketRange(size_t i) const {
[email protected]b7d08202011-01-25 17:29:39626 int range = ranges(i);
627 BucketDescriptionMap::const_iterator it = bucket_description_.find(range);
628 if (it == bucket_description_.end())
629 return Histogram::GetAsciiBucketRange(i);
630 return it->second;
631}
632
633bool LinearHistogram::PrintEmptyBucket(size_t index) const {
634 return bucket_description_.find(ranges(index)) == bucket_description_.end();
635}
636
[email protected]34d062322012-08-01 21:34:08637// static
638void LinearHistogram::InitializeBucketRanges(Sample minimum,
639 Sample maximum,
640 size_t bucket_count,
641 BucketRanges* ranges) {
642 DCHECK_EQ(ranges->size(), bucket_count + 1);
643 double min = minimum;
644 double max = maximum;
645 size_t i;
646 for (i = 1; i < bucket_count; ++i) {
647 double linear_range =
648 (min * (bucket_count -1 - i) + max * (i - 1)) / (bucket_count - 2);
649 ranges->set_range(i, static_cast<Sample>(linear_range + 0.5));
650 }
651 ranges->set_range(ranges->size() - 1, HistogramBase::kSampleType_MAX);
652 ranges->ResetChecksum();
653}
[email protected]b7d08202011-01-25 17:29:39654
[email protected]c50c21d2013-01-11 21:52:44655// static
656HistogramBase* LinearHistogram::DeserializeInfoImpl(PickleIterator* iter) {
657 string histogram_name;
658 int flags;
659 int declared_min;
660 int declared_max;
661 uint64 bucket_count;
662 uint32 range_checksum;
663
664 if (!ReadHistogramArguments(iter, &histogram_name, &flags, &declared_min,
665 &declared_max, &bucket_count, &range_checksum)) {
666 return NULL;
667 }
668
669 HistogramBase* histogram = LinearHistogram::FactoryGet(
670 histogram_name, declared_min, declared_max, bucket_count, flags);
671 if (!ValidateRangeChecksum(*histogram, range_checksum)) {
672 // The serialized histogram might be corrupted.
673 return NULL;
674 }
675 return histogram;
676}
677
initial.commitd7cae122008-07-26 21:49:38678//------------------------------------------------------------------------------
[email protected]e8829a192009-12-06 00:09:37679// This section provides implementation for BooleanHistogram.
680//------------------------------------------------------------------------------
681
[email protected]de415552013-01-23 04:12:17682HistogramBase* BooleanHistogram::FactoryGet(const string& name, int32 flags) {
[email protected]cc7dec212013-03-01 03:53:25683 HistogramBase* histogram = StatisticsRecorder::FindHistogram(name);
[email protected]993ae742012-07-18 18:06:30684 if (!histogram) {
[email protected]81ce9f3b2011-04-05 04:48:53685 // To avoid racy destruction at shutdown, the following will be leaked.
[email protected]34d062322012-08-01 21:34:08686 BucketRanges* ranges = new BucketRanges(4);
687 LinearHistogram::InitializeBucketRanges(1, 2, 3, ranges);
688 const BucketRanges* registered_ranges =
689 StatisticsRecorder::RegisterOrDeleteDuplicateRanges(ranges);
690
691 BooleanHistogram* tentative_histogram =
692 new BooleanHistogram(name, registered_ranges);
[email protected]263a17a2012-08-16 03:03:54693
[email protected]81ce9f3b2011-04-05 04:48:53694 tentative_histogram->SetFlags(flags);
695 histogram =
696 StatisticsRecorder::RegisterOrDeleteDuplicate(tentative_histogram);
[email protected]e8829a192009-12-06 00:09:37697 }
698
[email protected]cc7dec212013-03-01 03:53:25699 DCHECK_EQ(BOOLEAN_HISTOGRAM, histogram->GetHistogramType());
[email protected]e8829a192009-12-06 00:09:37700 return histogram;
701}
702
[email protected]07c02402012-10-31 06:20:25703HistogramType BooleanHistogram::GetHistogramType() const {
[email protected]5d91c9e2010-07-28 17:25:28704 return BOOLEAN_HISTOGRAM;
705}
706
[email protected]34d062322012-08-01 21:34:08707BooleanHistogram::BooleanHistogram(const string& name,
708 const BucketRanges* ranges)
709 : LinearHistogram(name, 1, 2, 3, ranges) {}
initial.commitd7cae122008-07-26 21:49:38710
[email protected]c50c21d2013-01-11 21:52:44711HistogramBase* BooleanHistogram::DeserializeInfoImpl(PickleIterator* iter) {
712 string histogram_name;
713 int flags;
714 int declared_min;
715 int declared_max;
716 uint64 bucket_count;
717 uint32 range_checksum;
718
719 if (!ReadHistogramArguments(iter, &histogram_name, &flags, &declared_min,
720 &declared_max, &bucket_count, &range_checksum)) {
721 return NULL;
722 }
723
724 HistogramBase* histogram = BooleanHistogram::FactoryGet(
725 histogram_name, flags);
726 if (!ValidateRangeChecksum(*histogram, range_checksum)) {
727 // The serialized histogram might be corrupted.
728 return NULL;
729 }
730 return histogram;
731}
732
initial.commitd7cae122008-07-26 21:49:38733//------------------------------------------------------------------------------
[email protected]70cc56e42010-04-29 22:39:55734// CustomHistogram:
735//------------------------------------------------------------------------------
736
[email protected]de415552013-01-23 04:12:17737HistogramBase* CustomHistogram::FactoryGet(const string& name,
738 const vector<Sample>& custom_ranges,
739 int32 flags) {
[email protected]34d062322012-08-01 21:34:08740 CHECK(ValidateCustomRanges(custom_ranges));
[email protected]70cc56e42010-04-29 22:39:55741
[email protected]cc7dec212013-03-01 03:53:25742 HistogramBase* histogram = StatisticsRecorder::FindHistogram(name);
[email protected]993ae742012-07-18 18:06:30743 if (!histogram) {
[email protected]34d062322012-08-01 21:34:08744 BucketRanges* ranges = CreateBucketRangesFromCustomRanges(custom_ranges);
745 const BucketRanges* registered_ranges =
746 StatisticsRecorder::RegisterOrDeleteDuplicateRanges(ranges);
747
[email protected]81ce9f3b2011-04-05 04:48:53748 // To avoid racy destruction at shutdown, the following will be leaked.
[email protected]34d062322012-08-01 21:34:08749 CustomHistogram* tentative_histogram =
750 new CustomHistogram(name, registered_ranges);
[email protected]263a17a2012-08-16 03:03:54751
[email protected]81ce9f3b2011-04-05 04:48:53752 tentative_histogram->SetFlags(flags);
[email protected]34d062322012-08-01 21:34:08753
[email protected]81ce9f3b2011-04-05 04:48:53754 histogram =
755 StatisticsRecorder::RegisterOrDeleteDuplicate(tentative_histogram);
[email protected]70cc56e42010-04-29 22:39:55756 }
757
[email protected]cc7dec212013-03-01 03:53:25758 DCHECK_EQ(histogram->GetHistogramType(), CUSTOM_HISTOGRAM);
[email protected]70cc56e42010-04-29 22:39:55759 return histogram;
760}
761
[email protected]07c02402012-10-31 06:20:25762HistogramType CustomHistogram::GetHistogramType() const {
[email protected]5d91c9e2010-07-28 17:25:28763 return CUSTOM_HISTOGRAM;
764}
765
[email protected]961fefb2011-05-24 13:59:58766// static
[email protected]34d062322012-08-01 21:34:08767vector<Sample> CustomHistogram::ArrayToCustomRanges(
[email protected]961fefb2011-05-24 13:59:58768 const Sample* values, size_t num_values) {
[email protected]34d062322012-08-01 21:34:08769 vector<Sample> all_values;
[email protected]961fefb2011-05-24 13:59:58770 for (size_t i = 0; i < num_values; ++i) {
771 Sample value = values[i];
772 all_values.push_back(value);
773
774 // Ensure that a guard bucket is added. If we end up with duplicate
775 // values, FactoryGet will take care of removing them.
776 all_values.push_back(value + 1);
777 }
778 return all_values;
779}
780
[email protected]34d062322012-08-01 21:34:08781CustomHistogram::CustomHistogram(const string& name,
782 const BucketRanges* ranges)
783 : Histogram(name,
784 ranges->range(1),
785 ranges->range(ranges->size() - 2),
786 ranges->size() - 1,
787 ranges) {}
[email protected]70cc56e42010-04-29 22:39:55788
[email protected]c50c21d2013-01-11 21:52:44789bool CustomHistogram::SerializeInfoImpl(Pickle* pickle) const {
790 if (!Histogram::SerializeInfoImpl(pickle))
791 return false;
[email protected]cd56dff2011-11-13 04:19:15792
[email protected]c50c21d2013-01-11 21:52:44793 // Serialize ranges. First and last ranges are alwasy 0 and INT_MAX, so don't
794 // write them.
795 for (size_t i = 1; i < bucket_ranges()->size() - 1; ++i) {
796 if (!pickle->WriteInt(bucket_ranges()->range(i)))
[email protected]cd56dff2011-11-13 04:19:15797 return false;
798 }
799 return true;
800}
801
[email protected]70cc56e42010-04-29 22:39:55802double CustomHistogram::GetBucketSize(Count current, size_t i) const {
803 return 1;
804}
805
[email protected]34d062322012-08-01 21:34:08806// static
[email protected]c50c21d2013-01-11 21:52:44807HistogramBase* CustomHistogram::DeserializeInfoImpl(PickleIterator* iter) {
808 string histogram_name;
809 int flags;
810 int declared_min;
811 int declared_max;
812 uint64 bucket_count;
813 uint32 range_checksum;
814
815 if (!ReadHistogramArguments(iter, &histogram_name, &flags, &declared_min,
816 &declared_max, &bucket_count, &range_checksum)) {
817 return NULL;
818 }
819
820 // First and last ranges are not serialized.
821 vector<Sample> sample_ranges(bucket_count - 1);
822
823 for (size_t i = 0; i < sample_ranges.size(); ++i) {
824 if (!iter->ReadInt(&sample_ranges[i]))
825 return NULL;
826 }
827
828 HistogramBase* histogram = CustomHistogram::FactoryGet(
829 histogram_name, sample_ranges, flags);
830 if (!ValidateRangeChecksum(*histogram, range_checksum)) {
831 // The serialized histogram might be corrupted.
832 return NULL;
833 }
834 return histogram;
835}
836
837// static
[email protected]34d062322012-08-01 21:34:08838bool CustomHistogram::ValidateCustomRanges(
839 const vector<Sample>& custom_ranges) {
[email protected]640d95ef2012-08-04 06:23:03840 bool has_valid_range = false;
[email protected]34d062322012-08-01 21:34:08841 for (size_t i = 0; i < custom_ranges.size(); i++) {
[email protected]640d95ef2012-08-04 06:23:03842 Sample sample = custom_ranges[i];
843 if (sample < 0 || sample > HistogramBase::kSampleType_MAX - 1)
[email protected]34d062322012-08-01 21:34:08844 return false;
[email protected]640d95ef2012-08-04 06:23:03845 if (sample != 0)
846 has_valid_range = true;
[email protected]34d062322012-08-01 21:34:08847 }
[email protected]640d95ef2012-08-04 06:23:03848 return has_valid_range;
[email protected]34d062322012-08-01 21:34:08849}
850
851// static
852BucketRanges* CustomHistogram::CreateBucketRangesFromCustomRanges(
853 const vector<Sample>& custom_ranges) {
854 // Remove the duplicates in the custom ranges array.
855 vector<int> ranges = custom_ranges;
856 ranges.push_back(0); // Ensure we have a zero value.
857 ranges.push_back(HistogramBase::kSampleType_MAX);
858 std::sort(ranges.begin(), ranges.end());
859 ranges.erase(std::unique(ranges.begin(), ranges.end()), ranges.end());
860
861 BucketRanges* bucket_ranges = new BucketRanges(ranges.size());
862 for (size_t i = 0; i < ranges.size(); i++) {
863 bucket_ranges->set_range(i, ranges[i]);
864 }
865 bucket_ranges->ResetChecksum();
866 return bucket_ranges;
867}
868
[email protected]835d7c82010-10-14 04:38:38869} // namespace base