blob: 6bab0eb43c0673d0cb3309de29d62598602db595 [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]d529cb02013-06-10 19:06:5723#include "base/strings/string_util.h"
24#include "base/strings/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);
[email protected]15ce3842013-06-27 14:38:45100 InitializeBucketRanges(minimum, maximum, ranges);
[email protected]34d062322012-08-01 21:34:08101 const BucketRanges* registered_ranges =
102 StatisticsRecorder::RegisterOrDeleteDuplicateRanges(ranges);
103
104 Histogram* tentative_histogram =
[email protected]15ce3842013-06-27 14:38:45105 new Histogram(name, minimum, maximum, 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]65796dc2014-03-13 14:08:18113 if (!histogram->HasConstructionArguments(minimum, maximum, bucket_count)) {
114 // The construction arguments do not match the existing histogram. This can
115 // come about if an extension updates in the middle of a chrome run and has
116 // changed one of them, or simply by bad code within Chrome itself. We
117 // return NULL here with the expectation that bad code in Chrome will crash
118 // on dereference, but extension/Pepper APIs will guard against NULL and not
119 // crash.
120 DLOG(ERROR) << "Histogram " << name << " has bad construction arguments";
121 return NULL;
122 }
[email protected]e8829a192009-12-06 00:09:37123 return histogram;
124}
125
[email protected]de415552013-01-23 04:12:17126HistogramBase* Histogram::FactoryTimeGet(const string& name,
127 TimeDelta minimum,
128 TimeDelta maximum,
129 size_t bucket_count,
130 int32 flags) {
pkasting9cf9b94a2014-10-01 22:18:43131 return FactoryGet(name, static_cast<Sample>(minimum.InMilliseconds()),
132 static_cast<Sample>(maximum.InMilliseconds()), bucket_count,
133 flags);
[email protected]34d062322012-08-01 21:34:08134}
135
[email protected]34d062322012-08-01 21:34:08136// Calculate what range of values are held in each bucket.
137// We have to be careful that we don't pick a ratio between starting points in
138// consecutive buckets that is sooo small, that the integer bounds are the same
139// (effectively making one bucket get no values). We need to avoid:
140// ranges(i) == ranges(i + 1)
141// To avoid that, we just do a fine-grained bucket width as far as we need to
142// until we get a ratio that moves us along at least 2 units at a time. From
143// that bucket onward we do use the exponential growth of buckets.
144//
145// static
146void Histogram::InitializeBucketRanges(Sample minimum,
147 Sample maximum,
[email protected]34d062322012-08-01 21:34:08148 BucketRanges* ranges) {
[email protected]34d062322012-08-01 21:34:08149 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);
[email protected]15ce3842013-06-27 14:38:45155 size_t bucket_count = ranges->bucket_count();
[email protected]34d062322012-08-01 21:34:08156 while (bucket_count > ++bucket_index) {
157 double log_current;
158 log_current = log(static_cast<double>(current));
159 // Calculate the count'th root of the range.
160 log_ratio = (log_max - log_current) / (bucket_count - bucket_index);
161 // See where the next bucket would start.
162 log_next = log_current + log_ratio;
163 Sample next;
164 next = static_cast<int>(floor(exp(log_next) + 0.5));
165 if (next > current)
166 current = next;
167 else
168 ++current; // Just do a narrow bucket, and keep trying.
169 ranges->set_range(bucket_index, current);
170 }
[email protected]15ce3842013-06-27 14:38:45171 ranges->set_range(ranges->bucket_count(), HistogramBase::kSampleType_MAX);
[email protected]34d062322012-08-01 21:34:08172 ranges->ResetChecksum();
173}
174
[email protected]2f7d9cd2012-09-22 03:42:12175// static
176const int Histogram::kCommonRaceBasedCountMismatch = 5;
[email protected]34d062322012-08-01 21:34:08177
[email protected]cc7dec212013-03-01 03:53:25178int Histogram::FindCorruption(const HistogramSamples& samples) const {
[email protected]34d062322012-08-01 21:34:08179 int inconsistencies = NO_INCONSISTENCIES;
180 Sample previous_range = -1; // Bottom range is always 0.
[email protected]34d062322012-08-01 21:34:08181 for (size_t index = 0; index < bucket_count(); ++index) {
[email protected]34d062322012-08-01 21:34:08182 int new_range = ranges(index);
183 if (previous_range >= new_range)
184 inconsistencies |= BUCKET_ORDER_ERROR;
185 previous_range = new_range;
186 }
187
188 if (!bucket_ranges()->HasValidChecksum())
189 inconsistencies |= RANGE_CHECKSUM_ERROR;
190
[email protected]2f7d9cd2012-09-22 03:42:12191 int64 delta64 = samples.redundant_count() - samples.TotalCount();
[email protected]34d062322012-08-01 21:34:08192 if (delta64 != 0) {
193 int delta = static_cast<int>(delta64);
194 if (delta != delta64)
195 delta = INT_MAX; // Flag all giant errors as INT_MAX.
[email protected]34d062322012-08-01 21:34:08196 if (delta > 0) {
197 UMA_HISTOGRAM_COUNTS("Histogram.InconsistentCountHigh", delta);
198 if (delta > kCommonRaceBasedCountMismatch)
199 inconsistencies |= COUNT_HIGH_ERROR;
200 } else {
201 DCHECK_GT(0, delta);
202 UMA_HISTOGRAM_COUNTS("Histogram.InconsistentCountLow", -delta);
203 if (-delta > kCommonRaceBasedCountMismatch)
204 inconsistencies |= COUNT_LOW_ERROR;
205 }
206 }
[email protected]cc7dec212013-03-01 03:53:25207 return inconsistencies;
[email protected]34d062322012-08-01 21:34:08208}
209
[email protected]34d062322012-08-01 21:34:08210Sample Histogram::ranges(size_t i) const {
211 return bucket_ranges_->range(i);
212}
213
214size_t Histogram::bucket_count() const {
[email protected]15ce3842013-06-27 14:38:45215 return bucket_ranges_->bucket_count();
[email protected]34d062322012-08-01 21:34:08216}
217
[email protected]34d062322012-08-01 21:34:08218// static
219bool Histogram::InspectConstructionArguments(const string& name,
220 Sample* minimum,
221 Sample* maximum,
222 size_t* bucket_count) {
223 // Defensive code for backward compatibility.
224 if (*minimum < 1) {
[email protected]a5c7bd792012-08-02 00:29:04225 DVLOG(1) << "Histogram: " << name << " has bad minimum: " << *minimum;
[email protected]34d062322012-08-01 21:34:08226 *minimum = 1;
227 }
228 if (*maximum >= kSampleType_MAX) {
[email protected]a5c7bd792012-08-02 00:29:04229 DVLOG(1) << "Histogram: " << name << " has bad maximum: " << *maximum;
230 *maximum = kSampleType_MAX - 1;
[email protected]34d062322012-08-01 21:34:08231 }
[email protected]e184be902012-08-07 04:49:24232 if (*bucket_count >= kBucketCount_MAX) {
233 DVLOG(1) << "Histogram: " << name << " has bad bucket_count: "
234 << *bucket_count;
235 *bucket_count = kBucketCount_MAX - 1;
236 }
[email protected]34d062322012-08-01 21:34:08237
[email protected]e184be902012-08-07 04:49:24238 if (*minimum >= *maximum)
239 return false;
240 if (*bucket_count < 3)
[email protected]34d062322012-08-01 21:34:08241 return false;
242 if (*bucket_count > static_cast<size_t>(*maximum - *minimum + 2))
243 return false;
244 return true;
245}
246
[email protected]07c02402012-10-31 06:20:25247HistogramType Histogram::GetHistogramType() const {
248 return HISTOGRAM;
249}
250
[email protected]15ce3842013-06-27 14:38:45251bool Histogram::HasConstructionArguments(Sample expected_minimum,
252 Sample expected_maximum,
253 size_t expected_bucket_count) const {
254 return ((expected_minimum == declared_min_) &&
255 (expected_maximum == declared_max_) &&
256 (expected_bucket_count == bucket_count()));
[email protected]abae9b022012-10-24 08:18:52257}
258
259void Histogram::Add(int value) {
260 DCHECK_EQ(0, ranges(0));
[email protected]15ce3842013-06-27 14:38:45261 DCHECK_EQ(kSampleType_MAX, ranges(bucket_count()));
[email protected]abae9b022012-10-24 08:18:52262
263 if (value > kSampleType_MAX - 1)
264 value = kSampleType_MAX - 1;
265 if (value < 0)
266 value = 0;
267 samples_->Accumulate(value, 1);
268}
269
270scoped_ptr<HistogramSamples> Histogram::SnapshotSamples() const {
271 return SnapshotSampleVector().PassAs<HistogramSamples>();
272}
273
[email protected]c50c21d2013-01-11 21:52:44274void Histogram::AddSamples(const HistogramSamples& samples) {
275 samples_->Add(samples);
276}
277
278bool Histogram::AddSamplesFromPickle(PickleIterator* iter) {
279 return samples_->AddFromPickle(iter);
280}
281
[email protected]abae9b022012-10-24 08:18:52282// The following methods provide a graphical histogram display.
283void Histogram::WriteHTMLGraph(string* output) const {
284 // TBD(jar) Write a nice HTML bar chart, with divs an mouse-overs etc.
285 output->append("<PRE>");
286 WriteAsciiImpl(true, "<br>", output);
287 output->append("</PRE>");
288}
289
290void Histogram::WriteAscii(string* output) const {
291 WriteAsciiImpl(true, "\n", output);
292}
293
[email protected]c50c21d2013-01-11 21:52:44294bool Histogram::SerializeInfoImpl(Pickle* pickle) const {
295 DCHECK(bucket_ranges()->HasValidChecksum());
296 return pickle->WriteString(histogram_name()) &&
297 pickle->WriteInt(flags()) &&
298 pickle->WriteInt(declared_min()) &&
299 pickle->WriteInt(declared_max()) &&
300 pickle->WriteUInt64(bucket_count()) &&
301 pickle->WriteUInt32(bucket_ranges()->checksum());
302}
303
[email protected]abae9b022012-10-24 08:18:52304Histogram::Histogram(const string& name,
305 Sample minimum,
306 Sample maximum,
[email protected]abae9b022012-10-24 08:18:52307 const BucketRanges* ranges)
308 : HistogramBase(name),
309 bucket_ranges_(ranges),
310 declared_min_(minimum),
[email protected]15ce3842013-06-27 14:38:45311 declared_max_(maximum) {
[email protected]abae9b022012-10-24 08:18:52312 if (ranges)
313 samples_.reset(new SampleVector(ranges));
314}
315
316Histogram::~Histogram() {
[email protected]abae9b022012-10-24 08:18:52317}
318
[email protected]34d062322012-08-01 21:34:08319bool Histogram::PrintEmptyBucket(size_t index) const {
320 return true;
321}
322
[email protected]34d062322012-08-01 21:34:08323// Use the actual bucket widths (like a linear histogram) until the widths get
324// over some transition value, and then use that transition width. Exponentials
325// get so big so fast (and we don't expect to see a lot of entries in the large
326// buckets), so we need this to make it possible to see what is going on and
327// not have 0-graphical-height buckets.
328double Histogram::GetBucketSize(Count current, size_t i) const {
329 DCHECK_GT(ranges(i + 1), ranges(i));
330 static const double kTransitionWidth = 5;
331 double denominator = ranges(i + 1) - ranges(i);
332 if (denominator > kTransitionWidth)
333 denominator = kTransitionWidth; // Stop trying to normalize.
334 return current/denominator;
335}
336
337const string Histogram::GetAsciiBucketRange(size_t i) const {
[email protected]f2bb3202013-04-05 21:21:54338 return GetSimpleAsciiBucketRange(ranges(i));
[email protected]34d062322012-08-01 21:34:08339}
340
[email protected]34d062322012-08-01 21:34:08341//------------------------------------------------------------------------------
342// Private methods
343
[email protected]c50c21d2013-01-11 21:52:44344// static
345HistogramBase* Histogram::DeserializeInfoImpl(PickleIterator* iter) {
346 string histogram_name;
347 int flags;
348 int declared_min;
349 int declared_max;
350 uint64 bucket_count;
351 uint32 range_checksum;
352
353 if (!ReadHistogramArguments(iter, &histogram_name, &flags, &declared_min,
354 &declared_max, &bucket_count, &range_checksum)) {
355 return NULL;
356 }
357
358 // Find or create the local version of the histogram in this process.
359 HistogramBase* histogram = Histogram::FactoryGet(
360 histogram_name, declared_min, declared_max, bucket_count, flags);
361
362 if (!ValidateRangeChecksum(*histogram, range_checksum)) {
363 // The serialized histogram might be corrupted.
364 return NULL;
365 }
366 return histogram;
367}
368
[email protected]877ef562012-10-20 02:56:18369scoped_ptr<SampleVector> Histogram::SnapshotSampleVector() const {
370 scoped_ptr<SampleVector> samples(new SampleVector(bucket_ranges()));
371 samples->Add(*samples_);
372 return samples.Pass();
373}
374
[email protected]34d062322012-08-01 21:34:08375void Histogram::WriteAsciiImpl(bool graph_it,
376 const string& newline,
377 string* output) const {
378 // Get local (stack) copies of all effectively volatile class data so that we
379 // are consistent across our output activities.
[email protected]877ef562012-10-20 02:56:18380 scoped_ptr<SampleVector> snapshot = SnapshotSampleVector();
[email protected]2f7d9cd2012-09-22 03:42:12381 Count sample_count = snapshot->TotalCount();
[email protected]34d062322012-08-01 21:34:08382
[email protected]2f7d9cd2012-09-22 03:42:12383 WriteAsciiHeader(*snapshot, sample_count, output);
[email protected]34d062322012-08-01 21:34:08384 output->append(newline);
385
386 // Prepare to normalize graphical rendering of bucket contents.
387 double max_size = 0;
388 if (graph_it)
[email protected]2f7d9cd2012-09-22 03:42:12389 max_size = GetPeakBucketSize(*snapshot);
[email protected]34d062322012-08-01 21:34:08390
391 // Calculate space needed to print bucket range numbers. Leave room to print
392 // nearly the largest bucket range without sliding over the histogram.
393 size_t largest_non_empty_bucket = bucket_count() - 1;
[email protected]2f7d9cd2012-09-22 03:42:12394 while (0 == snapshot->GetCountAtIndex(largest_non_empty_bucket)) {
[email protected]34d062322012-08-01 21:34:08395 if (0 == largest_non_empty_bucket)
396 break; // All buckets are empty.
397 --largest_non_empty_bucket;
398 }
399
400 // Calculate largest print width needed for any of our bucket range displays.
401 size_t print_width = 1;
402 for (size_t i = 0; i < bucket_count(); ++i) {
[email protected]2f7d9cd2012-09-22 03:42:12403 if (snapshot->GetCountAtIndex(i)) {
[email protected]34d062322012-08-01 21:34:08404 size_t width = GetAsciiBucketRange(i).size() + 1;
405 if (width > print_width)
406 print_width = width;
407 }
408 }
409
410 int64 remaining = sample_count;
411 int64 past = 0;
412 // Output the actual histogram graph.
413 for (size_t i = 0; i < bucket_count(); ++i) {
[email protected]2f7d9cd2012-09-22 03:42:12414 Count current = snapshot->GetCountAtIndex(i);
[email protected]34d062322012-08-01 21:34:08415 if (!current && !PrintEmptyBucket(i))
416 continue;
417 remaining -= current;
418 string range = GetAsciiBucketRange(i);
419 output->append(range);
420 for (size_t j = 0; range.size() + j < print_width + 1; ++j)
421 output->push_back(' ');
[email protected]2f7d9cd2012-09-22 03:42:12422 if (0 == current && i < bucket_count() - 1 &&
423 0 == snapshot->GetCountAtIndex(i + 1)) {
424 while (i < bucket_count() - 1 &&
425 0 == snapshot->GetCountAtIndex(i + 1)) {
[email protected]34d062322012-08-01 21:34:08426 ++i;
[email protected]2f7d9cd2012-09-22 03:42:12427 }
[email protected]34d062322012-08-01 21:34:08428 output->append("... ");
429 output->append(newline);
430 continue; // No reason to plot emptiness.
431 }
432 double current_size = GetBucketSize(current, i);
433 if (graph_it)
434 WriteAsciiBucketGraph(current_size, max_size, output);
435 WriteAsciiBucketContext(past, current, remaining, i, output);
436 output->append(newline);
437 past += current;
438 }
439 DCHECK_EQ(sample_count, past);
440}
441
[email protected]2f7d9cd2012-09-22 03:42:12442double Histogram::GetPeakBucketSize(const SampleVector& samples) const {
[email protected]34d062322012-08-01 21:34:08443 double max = 0;
444 for (size_t i = 0; i < bucket_count() ; ++i) {
[email protected]2f7d9cd2012-09-22 03:42:12445 double current_size = GetBucketSize(samples.GetCountAtIndex(i), i);
[email protected]34d062322012-08-01 21:34:08446 if (current_size > max)
447 max = current_size;
448 }
449 return max;
450}
451
[email protected]2f7d9cd2012-09-22 03:42:12452void Histogram::WriteAsciiHeader(const SampleVector& samples,
[email protected]34d062322012-08-01 21:34:08453 Count sample_count,
454 string* output) const {
455 StringAppendF(output,
456 "Histogram: %s recorded %d samples",
457 histogram_name().c_str(),
458 sample_count);
459 if (0 == sample_count) {
[email protected]2f7d9cd2012-09-22 03:42:12460 DCHECK_EQ(samples.sum(), 0);
[email protected]34d062322012-08-01 21:34:08461 } else {
[email protected]2f7d9cd2012-09-22 03:42:12462 double average = static_cast<float>(samples.sum()) / sample_count;
[email protected]34d062322012-08-01 21:34:08463
464 StringAppendF(output, ", average = %.1f", average);
465 }
[email protected]7c7a42752012-08-09 05:14:15466 if (flags() & ~kHexRangePrintingFlag)
467 StringAppendF(output, " (flags = 0x%x)", flags() & ~kHexRangePrintingFlag);
[email protected]34d062322012-08-01 21:34:08468}
469
470void Histogram::WriteAsciiBucketContext(const int64 past,
471 const Count current,
472 const int64 remaining,
473 const size_t i,
474 string* output) const {
475 double scaled_sum = (past + current + remaining) / 100.0;
476 WriteAsciiBucketValue(current, scaled_sum, output);
477 if (0 < i) {
478 double percentage = past / scaled_sum;
479 StringAppendF(output, " {%3.1f%%}", percentage);
480 }
481}
482
[email protected]24a7ec52012-10-08 10:31:50483void Histogram::GetParameters(DictionaryValue* params) const {
[email protected]07c02402012-10-31 06:20:25484 params->SetString("type", HistogramTypeToString(GetHistogramType()));
[email protected]24a7ec52012-10-08 10:31:50485 params->SetInteger("min", declared_min());
486 params->SetInteger("max", declared_max());
487 params->SetInteger("bucket_count", static_cast<int>(bucket_count()));
488}
489
[email protected]cdd98fc2013-05-10 09:32:58490void Histogram::GetCountAndBucketData(Count* count,
491 int64* sum,
492 ListValue* buckets) const {
[email protected]877ef562012-10-20 02:56:18493 scoped_ptr<SampleVector> snapshot = SnapshotSampleVector();
[email protected]24a7ec52012-10-08 10:31:50494 *count = snapshot->TotalCount();
[email protected]cdd98fc2013-05-10 09:32:58495 *sum = snapshot->sum();
[email protected]24a7ec52012-10-08 10:31:50496 size_t index = 0;
497 for (size_t i = 0; i < bucket_count(); ++i) {
498 Sample count = snapshot->GetCountAtIndex(i);
499 if (count > 0) {
500 scoped_ptr<DictionaryValue> bucket_value(new DictionaryValue());
501 bucket_value->SetInteger("low", ranges(i));
502 if (i != bucket_count() - 1)
503 bucket_value->SetInteger("high", ranges(i + 1));
504 bucket_value->SetInteger("count", count);
505 buckets->Set(index, bucket_value.release());
506 ++index;
507 }
508 }
509}
510
[email protected]34d062322012-08-01 21:34:08511//------------------------------------------------------------------------------
512// LinearHistogram: This histogram uses a traditional set of evenly spaced
513// buckets.
514//------------------------------------------------------------------------------
515
516LinearHistogram::~LinearHistogram() {}
517
[email protected]de415552013-01-23 04:12:17518HistogramBase* LinearHistogram::FactoryGet(const string& name,
519 Sample minimum,
520 Sample maximum,
521 size_t bucket_count,
522 int32 flags) {
[email protected]07c02402012-10-31 06:20:25523 return FactoryGetWithRangeDescription(
524 name, minimum, maximum, bucket_count, flags, NULL);
525}
526
[email protected]de415552013-01-23 04:12:17527HistogramBase* LinearHistogram::FactoryTimeGet(const string& name,
528 TimeDelta minimum,
529 TimeDelta maximum,
530 size_t bucket_count,
531 int32 flags) {
pkasting9cf9b94a2014-10-01 22:18:43532 return FactoryGet(name, static_cast<Sample>(minimum.InMilliseconds()),
533 static_cast<Sample>(maximum.InMilliseconds()), bucket_count,
534 flags);
[email protected]07c02402012-10-31 06:20:25535}
536
[email protected]de415552013-01-23 04:12:17537HistogramBase* LinearHistogram::FactoryGetWithRangeDescription(
[email protected]07c02402012-10-31 06:20:25538 const std::string& name,
539 Sample minimum,
540 Sample maximum,
541 size_t bucket_count,
542 int32 flags,
543 const DescriptionPair descriptions[]) {
[email protected]e184be902012-08-07 04:49:24544 bool valid_arguments = Histogram::InspectConstructionArguments(
545 name, &minimum, &maximum, &bucket_count);
546 DCHECK(valid_arguments);
[email protected]34d062322012-08-01 21:34:08547
[email protected]cc7dec212013-03-01 03:53:25548 HistogramBase* histogram = StatisticsRecorder::FindHistogram(name);
[email protected]34d062322012-08-01 21:34:08549 if (!histogram) {
550 // To avoid racy destruction at shutdown, the following will be leaked.
551 BucketRanges* ranges = new BucketRanges(bucket_count + 1);
[email protected]15ce3842013-06-27 14:38:45552 InitializeBucketRanges(minimum, maximum, ranges);
[email protected]34d062322012-08-01 21:34:08553 const BucketRanges* registered_ranges =
554 StatisticsRecorder::RegisterOrDeleteDuplicateRanges(ranges);
555
556 LinearHistogram* tentative_histogram =
[email protected]15ce3842013-06-27 14:38:45557 new LinearHistogram(name, minimum, maximum, registered_ranges);
[email protected]263a17a2012-08-16 03:03:54558
[email protected]07c02402012-10-31 06:20:25559 // Set range descriptions.
560 if (descriptions) {
561 for (int i = 0; descriptions[i].description; ++i) {
562 tentative_histogram->bucket_description_[descriptions[i].sample] =
563 descriptions[i].description;
564 }
565 }
566
[email protected]34d062322012-08-01 21:34:08567 tentative_histogram->SetFlags(flags);
568 histogram =
569 StatisticsRecorder::RegisterOrDeleteDuplicate(tentative_histogram);
570 }
571
[email protected]cc7dec212013-03-01 03:53:25572 DCHECK_EQ(LINEAR_HISTOGRAM, histogram->GetHistogramType());
[email protected]65796dc2014-03-13 14:08:18573 if (!histogram->HasConstructionArguments(minimum, maximum, bucket_count)) {
574 // The construction arguments do not match the existing histogram. This can
575 // come about if an extension updates in the middle of a chrome run and has
576 // changed one of them, or simply by bad code within Chrome itself. We
577 // return NULL here with the expectation that bad code in Chrome will crash
578 // on dereference, but extension/Pepper APIs will guard against NULL and not
579 // crash.
580 DLOG(ERROR) << "Histogram " << name << " has bad construction arguments";
581 return NULL;
582 }
[email protected]34d062322012-08-01 21:34:08583 return histogram;
584}
585
[email protected]07c02402012-10-31 06:20:25586HistogramType LinearHistogram::GetHistogramType() const {
[email protected]b7d08202011-01-25 17:29:39587 return LINEAR_HISTOGRAM;
588}
589
[email protected]34d062322012-08-01 21:34:08590LinearHistogram::LinearHistogram(const string& name,
[email protected]835d7c82010-10-14 04:38:38591 Sample minimum,
592 Sample maximum,
[email protected]34d062322012-08-01 21:34:08593 const BucketRanges* ranges)
[email protected]15ce3842013-06-27 14:38:45594 : Histogram(name, minimum, maximum, ranges) {
initial.commitd7cae122008-07-26 21:49:38595}
596
initial.commitd7cae122008-07-26 21:49:38597double LinearHistogram::GetBucketSize(Count current, size_t i) const {
[email protected]2ef3748f2010-10-19 17:33:28598 DCHECK_GT(ranges(i + 1), ranges(i));
initial.commitd7cae122008-07-26 21:49:38599 // Adjacent buckets with different widths would have "surprisingly" many (few)
600 // samples in a histogram if we didn't normalize this way.
601 double denominator = ranges(i + 1) - ranges(i);
602 return current/denominator;
603}
604
[email protected]34d062322012-08-01 21:34:08605const string LinearHistogram::GetAsciiBucketRange(size_t i) const {
[email protected]b7d08202011-01-25 17:29:39606 int range = ranges(i);
607 BucketDescriptionMap::const_iterator it = bucket_description_.find(range);
608 if (it == bucket_description_.end())
609 return Histogram::GetAsciiBucketRange(i);
610 return it->second;
611}
612
613bool LinearHistogram::PrintEmptyBucket(size_t index) const {
614 return bucket_description_.find(ranges(index)) == bucket_description_.end();
615}
616
[email protected]34d062322012-08-01 21:34:08617// static
618void LinearHistogram::InitializeBucketRanges(Sample minimum,
619 Sample maximum,
[email protected]34d062322012-08-01 21:34:08620 BucketRanges* ranges) {
[email protected]34d062322012-08-01 21:34:08621 double min = minimum;
622 double max = maximum;
[email protected]15ce3842013-06-27 14:38:45623 size_t bucket_count = ranges->bucket_count();
624 for (size_t i = 1; i < bucket_count; ++i) {
[email protected]34d062322012-08-01 21:34:08625 double linear_range =
[email protected]15ce3842013-06-27 14:38:45626 (min * (bucket_count - 1 - i) + max * (i - 1)) / (bucket_count - 2);
[email protected]34d062322012-08-01 21:34:08627 ranges->set_range(i, static_cast<Sample>(linear_range + 0.5));
628 }
[email protected]15ce3842013-06-27 14:38:45629 ranges->set_range(ranges->bucket_count(), HistogramBase::kSampleType_MAX);
[email protected]34d062322012-08-01 21:34:08630 ranges->ResetChecksum();
631}
[email protected]b7d08202011-01-25 17:29:39632
[email protected]c50c21d2013-01-11 21:52:44633// static
634HistogramBase* LinearHistogram::DeserializeInfoImpl(PickleIterator* iter) {
635 string histogram_name;
636 int flags;
637 int declared_min;
638 int declared_max;
639 uint64 bucket_count;
640 uint32 range_checksum;
641
642 if (!ReadHistogramArguments(iter, &histogram_name, &flags, &declared_min,
643 &declared_max, &bucket_count, &range_checksum)) {
644 return NULL;
645 }
646
647 HistogramBase* histogram = LinearHistogram::FactoryGet(
648 histogram_name, declared_min, declared_max, bucket_count, flags);
649 if (!ValidateRangeChecksum(*histogram, range_checksum)) {
650 // The serialized histogram might be corrupted.
651 return NULL;
652 }
653 return histogram;
654}
655
initial.commitd7cae122008-07-26 21:49:38656//------------------------------------------------------------------------------
[email protected]e8829a192009-12-06 00:09:37657// This section provides implementation for BooleanHistogram.
658//------------------------------------------------------------------------------
659
[email protected]de415552013-01-23 04:12:17660HistogramBase* BooleanHistogram::FactoryGet(const string& name, int32 flags) {
[email protected]cc7dec212013-03-01 03:53:25661 HistogramBase* histogram = StatisticsRecorder::FindHistogram(name);
[email protected]993ae742012-07-18 18:06:30662 if (!histogram) {
[email protected]81ce9f3b2011-04-05 04:48:53663 // To avoid racy destruction at shutdown, the following will be leaked.
[email protected]34d062322012-08-01 21:34:08664 BucketRanges* ranges = new BucketRanges(4);
[email protected]15ce3842013-06-27 14:38:45665 LinearHistogram::InitializeBucketRanges(1, 2, ranges);
[email protected]34d062322012-08-01 21:34:08666 const BucketRanges* registered_ranges =
667 StatisticsRecorder::RegisterOrDeleteDuplicateRanges(ranges);
668
669 BooleanHistogram* tentative_histogram =
670 new BooleanHistogram(name, registered_ranges);
[email protected]263a17a2012-08-16 03:03:54671
[email protected]81ce9f3b2011-04-05 04:48:53672 tentative_histogram->SetFlags(flags);
673 histogram =
674 StatisticsRecorder::RegisterOrDeleteDuplicate(tentative_histogram);
[email protected]e8829a192009-12-06 00:09:37675 }
676
[email protected]cc7dec212013-03-01 03:53:25677 DCHECK_EQ(BOOLEAN_HISTOGRAM, histogram->GetHistogramType());
[email protected]e8829a192009-12-06 00:09:37678 return histogram;
679}
680
[email protected]07c02402012-10-31 06:20:25681HistogramType BooleanHistogram::GetHistogramType() const {
[email protected]5d91c9e2010-07-28 17:25:28682 return BOOLEAN_HISTOGRAM;
683}
684
[email protected]34d062322012-08-01 21:34:08685BooleanHistogram::BooleanHistogram(const string& name,
686 const BucketRanges* ranges)
[email protected]15ce3842013-06-27 14:38:45687 : LinearHistogram(name, 1, 2, ranges) {}
initial.commitd7cae122008-07-26 21:49:38688
[email protected]c50c21d2013-01-11 21:52:44689HistogramBase* BooleanHistogram::DeserializeInfoImpl(PickleIterator* iter) {
690 string histogram_name;
691 int flags;
692 int declared_min;
693 int declared_max;
694 uint64 bucket_count;
695 uint32 range_checksum;
696
697 if (!ReadHistogramArguments(iter, &histogram_name, &flags, &declared_min,
698 &declared_max, &bucket_count, &range_checksum)) {
699 return NULL;
700 }
701
702 HistogramBase* histogram = BooleanHistogram::FactoryGet(
703 histogram_name, flags);
704 if (!ValidateRangeChecksum(*histogram, range_checksum)) {
705 // The serialized histogram might be corrupted.
706 return NULL;
707 }
708 return histogram;
709}
710
initial.commitd7cae122008-07-26 21:49:38711//------------------------------------------------------------------------------
[email protected]70cc56e42010-04-29 22:39:55712// CustomHistogram:
713//------------------------------------------------------------------------------
714
[email protected]de415552013-01-23 04:12:17715HistogramBase* CustomHistogram::FactoryGet(const string& name,
716 const vector<Sample>& custom_ranges,
717 int32 flags) {
[email protected]34d062322012-08-01 21:34:08718 CHECK(ValidateCustomRanges(custom_ranges));
[email protected]70cc56e42010-04-29 22:39:55719
[email protected]cc7dec212013-03-01 03:53:25720 HistogramBase* histogram = StatisticsRecorder::FindHistogram(name);
[email protected]993ae742012-07-18 18:06:30721 if (!histogram) {
[email protected]34d062322012-08-01 21:34:08722 BucketRanges* ranges = CreateBucketRangesFromCustomRanges(custom_ranges);
723 const BucketRanges* registered_ranges =
724 StatisticsRecorder::RegisterOrDeleteDuplicateRanges(ranges);
725
[email protected]81ce9f3b2011-04-05 04:48:53726 // To avoid racy destruction at shutdown, the following will be leaked.
[email protected]34d062322012-08-01 21:34:08727 CustomHistogram* tentative_histogram =
728 new CustomHistogram(name, registered_ranges);
[email protected]263a17a2012-08-16 03:03:54729
[email protected]81ce9f3b2011-04-05 04:48:53730 tentative_histogram->SetFlags(flags);
[email protected]34d062322012-08-01 21:34:08731
[email protected]81ce9f3b2011-04-05 04:48:53732 histogram =
733 StatisticsRecorder::RegisterOrDeleteDuplicate(tentative_histogram);
[email protected]70cc56e42010-04-29 22:39:55734 }
735
[email protected]cc7dec212013-03-01 03:53:25736 DCHECK_EQ(histogram->GetHistogramType(), CUSTOM_HISTOGRAM);
[email protected]70cc56e42010-04-29 22:39:55737 return histogram;
738}
739
[email protected]07c02402012-10-31 06:20:25740HistogramType CustomHistogram::GetHistogramType() const {
[email protected]5d91c9e2010-07-28 17:25:28741 return CUSTOM_HISTOGRAM;
742}
743
[email protected]961fefb2011-05-24 13:59:58744// static
[email protected]34d062322012-08-01 21:34:08745vector<Sample> CustomHistogram::ArrayToCustomRanges(
[email protected]961fefb2011-05-24 13:59:58746 const Sample* values, size_t num_values) {
[email protected]34d062322012-08-01 21:34:08747 vector<Sample> all_values;
[email protected]961fefb2011-05-24 13:59:58748 for (size_t i = 0; i < num_values; ++i) {
749 Sample value = values[i];
750 all_values.push_back(value);
751
752 // Ensure that a guard bucket is added. If we end up with duplicate
753 // values, FactoryGet will take care of removing them.
754 all_values.push_back(value + 1);
755 }
756 return all_values;
757}
758
[email protected]34d062322012-08-01 21:34:08759CustomHistogram::CustomHistogram(const string& name,
760 const BucketRanges* ranges)
761 : Histogram(name,
762 ranges->range(1),
[email protected]15ce3842013-06-27 14:38:45763 ranges->range(ranges->bucket_count() - 1),
[email protected]34d062322012-08-01 21:34:08764 ranges) {}
[email protected]70cc56e42010-04-29 22:39:55765
[email protected]c50c21d2013-01-11 21:52:44766bool CustomHistogram::SerializeInfoImpl(Pickle* pickle) const {
767 if (!Histogram::SerializeInfoImpl(pickle))
768 return false;
[email protected]cd56dff2011-11-13 04:19:15769
[email protected]c50c21d2013-01-11 21:52:44770 // Serialize ranges. First and last ranges are alwasy 0 and INT_MAX, so don't
771 // write them.
[email protected]15ce3842013-06-27 14:38:45772 for (size_t i = 1; i < bucket_ranges()->bucket_count(); ++i) {
[email protected]c50c21d2013-01-11 21:52:44773 if (!pickle->WriteInt(bucket_ranges()->range(i)))
[email protected]cd56dff2011-11-13 04:19:15774 return false;
775 }
776 return true;
777}
778
[email protected]70cc56e42010-04-29 22:39:55779double CustomHistogram::GetBucketSize(Count current, size_t i) const {
780 return 1;
781}
782
[email protected]34d062322012-08-01 21:34:08783// static
[email protected]c50c21d2013-01-11 21:52:44784HistogramBase* CustomHistogram::DeserializeInfoImpl(PickleIterator* iter) {
785 string histogram_name;
786 int flags;
787 int declared_min;
788 int declared_max;
789 uint64 bucket_count;
790 uint32 range_checksum;
791
792 if (!ReadHistogramArguments(iter, &histogram_name, &flags, &declared_min,
793 &declared_max, &bucket_count, &range_checksum)) {
794 return NULL;
795 }
796
797 // First and last ranges are not serialized.
798 vector<Sample> sample_ranges(bucket_count - 1);
799
800 for (size_t i = 0; i < sample_ranges.size(); ++i) {
801 if (!iter->ReadInt(&sample_ranges[i]))
802 return NULL;
803 }
804
805 HistogramBase* histogram = CustomHistogram::FactoryGet(
806 histogram_name, sample_ranges, flags);
807 if (!ValidateRangeChecksum(*histogram, range_checksum)) {
808 // The serialized histogram might be corrupted.
809 return NULL;
810 }
811 return histogram;
812}
813
814// static
[email protected]34d062322012-08-01 21:34:08815bool CustomHistogram::ValidateCustomRanges(
816 const vector<Sample>& custom_ranges) {
[email protected]640d95ef2012-08-04 06:23:03817 bool has_valid_range = false;
[email protected]34d062322012-08-01 21:34:08818 for (size_t i = 0; i < custom_ranges.size(); i++) {
[email protected]640d95ef2012-08-04 06:23:03819 Sample sample = custom_ranges[i];
820 if (sample < 0 || sample > HistogramBase::kSampleType_MAX - 1)
[email protected]34d062322012-08-01 21:34:08821 return false;
[email protected]640d95ef2012-08-04 06:23:03822 if (sample != 0)
823 has_valid_range = true;
[email protected]34d062322012-08-01 21:34:08824 }
[email protected]640d95ef2012-08-04 06:23:03825 return has_valid_range;
[email protected]34d062322012-08-01 21:34:08826}
827
828// static
829BucketRanges* CustomHistogram::CreateBucketRangesFromCustomRanges(
830 const vector<Sample>& custom_ranges) {
831 // Remove the duplicates in the custom ranges array.
832 vector<int> ranges = custom_ranges;
833 ranges.push_back(0); // Ensure we have a zero value.
834 ranges.push_back(HistogramBase::kSampleType_MAX);
835 std::sort(ranges.begin(), ranges.end());
836 ranges.erase(std::unique(ranges.begin(), ranges.end()), ranges.end());
837
838 BucketRanges* bucket_ranges = new BucketRanges(ranges.size());
839 for (size_t i = 0; i < ranges.size(); i++) {
840 bucket_ranges->set_range(i, ranges[i]);
841 }
842 bucket_ranges->ResetChecksum();
843 return bucket_ranges;
844}
845
[email protected]835d7c82010-10-14 04:38:38846} // namespace base