blob: 1526cd8a26ec0162c327538aa9f1350893549ce1 [file] [log] [blame]
[email protected]f1633932010-08-17 23:05:281// Copyright (c) 2010 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
initial.commitd7cae122008-07-26 21:49:3817#include "base/logging.h"
[email protected]3f383852009-04-03 18:18:5518#include "base/pickle.h"
[email protected]f1633932010-08-17 23:05:2819#include "base/stringprintf.h"
[email protected]bc581a682011-01-01 23:16:2020#include "base/synchronization/lock.h"
initial.commitd7cae122008-07-26 21:49:3821
[email protected]835d7c82010-10-14 04:38:3822namespace base {
[email protected]e1acf6f2008-10-27 20:43:3323
initial.commitd7cae122008-07-26 21:49:3824typedef Histogram::Count Count;
25
[email protected]2753b392009-12-28 06:59:5226scoped_refptr<Histogram> Histogram::FactoryGet(const std::string& name,
27 Sample minimum, Sample maximum, size_t bucket_count, Flags flags) {
[email protected]e8829a192009-12-06 00:09:3728 scoped_refptr<Histogram> histogram(NULL);
29
30 // Defensive code.
[email protected]2ef3748f2010-10-19 17:33:2831 if (minimum < 1)
[email protected]e8829a192009-12-06 00:09:3732 minimum = 1;
[email protected]2ef3748f2010-10-19 17:33:2833 if (maximum > kSampleType_MAX - 1)
[email protected]e8829a192009-12-06 00:09:3734 maximum = kSampleType_MAX - 1;
35
[email protected]f2bc0cb52010-06-25 15:55:1536 if (!StatisticsRecorder::FindHistogram(name, &histogram)) {
[email protected]e8829a192009-12-06 00:09:3737 histogram = new Histogram(name, minimum, maximum, bucket_count);
[email protected]f2bc0cb52010-06-25 15:55:1538 StatisticsRecorder::FindHistogram(name, &histogram);
[email protected]e8829a192009-12-06 00:09:3739 }
40
[email protected]2ef3748f2010-10-19 17:33:2841 DCHECK_EQ(HISTOGRAM, histogram->histogram_type());
[email protected]e8829a192009-12-06 00:09:3742 DCHECK(histogram->HasConstructorArguments(minimum, maximum, bucket_count));
[email protected]2753b392009-12-28 06:59:5243 histogram->SetFlags(flags);
[email protected]e8829a192009-12-06 00:09:3744 return histogram;
45}
46
[email protected]a764bf5e2010-06-02 21:31:4447scoped_refptr<Histogram> Histogram::FactoryTimeGet(const std::string& name,
[email protected]835d7c82010-10-14 04:38:3848 TimeDelta minimum,
49 TimeDelta maximum,
50 size_t bucket_count,
51 Flags flags) {
[email protected]2753b392009-12-28 06:59:5252 return FactoryGet(name, minimum.InMilliseconds(), maximum.InMilliseconds(),
53 bucket_count, flags);
[email protected]e8829a192009-12-06 00:09:3754}
55
56Histogram::Histogram(const std::string& name, Sample minimum,
initial.commitd7cae122008-07-26 21:49:3857 Sample maximum, size_t bucket_count)
[email protected]e6f02ab2009-04-10 22:29:2958 : histogram_name_(name),
initial.commitd7cae122008-07-26 21:49:3859 declared_min_(minimum),
60 declared_max_(maximum),
61 bucket_count_(bucket_count),
[email protected]2753b392009-12-28 06:59:5262 flags_(kNoFlags),
initial.commitd7cae122008-07-26 21:49:3863 ranges_(bucket_count + 1, 0),
[email protected]93a41d72010-11-03 23:36:2464 range_checksum_(0),
[email protected]e8829a192009-12-06 00:09:3765 sample_() {
initial.commitd7cae122008-07-26 21:49:3866 Initialize();
67}
68
[email protected]e8829a192009-12-06 00:09:3769Histogram::Histogram(const std::string& name, TimeDelta minimum,
initial.commitd7cae122008-07-26 21:49:3870 TimeDelta maximum, size_t bucket_count)
[email protected]e6f02ab2009-04-10 22:29:2971 : histogram_name_(name),
initial.commitd7cae122008-07-26 21:49:3872 declared_min_(static_cast<int> (minimum.InMilliseconds())),
73 declared_max_(static_cast<int> (maximum.InMilliseconds())),
74 bucket_count_(bucket_count),
[email protected]2753b392009-12-28 06:59:5275 flags_(kNoFlags),
initial.commitd7cae122008-07-26 21:49:3876 ranges_(bucket_count + 1, 0),
[email protected]93a41d72010-11-03 23:36:2477 range_checksum_(0),
[email protected]e8829a192009-12-06 00:09:3778 sample_() {
initial.commitd7cae122008-07-26 21:49:3879 Initialize();
80}
81
82Histogram::~Histogram() {
[email protected]e8829a192009-12-06 00:09:3783 if (StatisticsRecorder::dump_on_exit()) {
84 std::string output;
85 WriteAscii(true, "\n", &output);
[email protected]89fb65a2010-10-18 21:53:0086 LOG(INFO) << output;
[email protected]e8829a192009-12-06 00:09:3787 }
88
initial.commitd7cae122008-07-26 21:49:3889 // Just to make sure most derived class did this properly...
90 DCHECK(ValidateBucketRanges());
[email protected]93a41d72010-11-03 23:36:2491 DCHECK(HasValidRangeChecksum());
initial.commitd7cae122008-07-26 21:49:3892}
93
[email protected]5d91c9e2010-07-28 17:25:2894bool Histogram::PrintEmptyBucket(size_t index) const {
95 return true;
96}
97
initial.commitd7cae122008-07-26 21:49:3898void Histogram::Add(int value) {
[email protected]2ef3748f2010-10-19 17:33:2899 if (value > kSampleType_MAX - 1)
initial.commitd7cae122008-07-26 21:49:38100 value = kSampleType_MAX - 1;
initial.commitd7cae122008-07-26 21:49:38101 if (value < 0)
102 value = 0;
103 size_t index = BucketIndex(value);
[email protected]2ef3748f2010-10-19 17:33:28104 DCHECK_GE(value, ranges(index));
105 DCHECK_LT(value, ranges(index + 1));
initial.commitd7cae122008-07-26 21:49:38106 Accumulate(value, 1, index);
107}
108
[email protected]5d91c9e2010-07-28 17:25:28109void Histogram::AddBoolean(bool value) {
110 DCHECK(false);
111}
112
[email protected]55e57d42009-02-25 06:10:17113void Histogram::AddSampleSet(const SampleSet& sample) {
114 sample_.Add(sample);
115}
116
[email protected]5d91c9e2010-07-28 17:25:28117void Histogram::SetRangeDescriptions(const DescriptionPair descriptions[]) {
118 DCHECK(false);
119}
120
initial.commitd7cae122008-07-26 21:49:38121// The following methods provide a graphical histogram display.
122void Histogram::WriteHTMLGraph(std::string* output) const {
123 // TBD(jar) Write a nice HTML bar chart, with divs an mouse-overs etc.
124 output->append("<PRE>");
125 WriteAscii(true, "<br>", output);
126 output->append("</PRE>");
127}
128
129void Histogram::WriteAscii(bool graph_it, const std::string& newline,
130 std::string* output) const {
131 // Get local (stack) copies of all effectively volatile class data so that we
132 // are consistent across our output activities.
133 SampleSet snapshot;
134 SnapshotSample(&snapshot);
135 Count sample_count = snapshot.TotalCount();
136
137 WriteAsciiHeader(snapshot, sample_count, output);
138 output->append(newline);
139
140 // Prepare to normalize graphical rendering of bucket contents.
141 double max_size = 0;
142 if (graph_it)
143 max_size = GetPeakBucketSize(snapshot);
144
145 // Calculate space needed to print bucket range numbers. Leave room to print
146 // nearly the largest bucket range without sliding over the histogram.
[email protected]e2951cf2008-09-24 23:51:25147 size_t largest_non_empty_bucket = bucket_count() - 1;
148 while (0 == snapshot.counts(largest_non_empty_bucket)) {
initial.commitd7cae122008-07-26 21:49:38149 if (0 == largest_non_empty_bucket)
150 break; // All buckets are empty.
[email protected]55e57d42009-02-25 06:10:17151 --largest_non_empty_bucket;
initial.commitd7cae122008-07-26 21:49:38152 }
153
154 // Calculate largest print width needed for any of our bucket range displays.
155 size_t print_width = 1;
[email protected]e2951cf2008-09-24 23:51:25156 for (size_t i = 0; i < bucket_count(); ++i) {
initial.commitd7cae122008-07-26 21:49:38157 if (snapshot.counts(i)) {
158 size_t width = GetAsciiBucketRange(i).size() + 1;
159 if (width > print_width)
160 print_width = width;
161 }
162 }
163
164 int64 remaining = sample_count;
165 int64 past = 0;
166 // Output the actual histogram graph.
[email protected]55e57d42009-02-25 06:10:17167 for (size_t i = 0; i < bucket_count(); ++i) {
initial.commitd7cae122008-07-26 21:49:38168 Count current = snapshot.counts(i);
169 if (!current && !PrintEmptyBucket(i))
170 continue;
171 remaining -= current;
[email protected]34b2b002009-11-20 06:53:28172 std::string range = GetAsciiBucketRange(i);
173 output->append(range);
174 for (size_t j = 0; range.size() + j < print_width + 1; ++j)
175 output->push_back(' ');
[email protected]e2951cf2008-09-24 23:51:25176 if (0 == current && i < bucket_count() - 1 && 0 == snapshot.counts(i + 1)) {
177 while (i < bucket_count() - 1 && 0 == snapshot.counts(i + 1))
[email protected]55e57d42009-02-25 06:10:17178 ++i;
initial.commitd7cae122008-07-26 21:49:38179 output->append("... ");
180 output->append(newline);
181 continue; // No reason to plot emptiness.
182 }
183 double current_size = GetBucketSize(current, i);
184 if (graph_it)
185 WriteAsciiBucketGraph(current_size, max_size, output);
186 WriteAsciiBucketContext(past, current, remaining, i, output);
187 output->append(newline);
188 past += current;
189 }
[email protected]2ef3748f2010-10-19 17:33:28190 DCHECK_EQ(sample_count, past);
initial.commitd7cae122008-07-26 21:49:38191}
192
193bool Histogram::ValidateBucketRanges() const {
194 // Standard assertions that all bucket ranges should satisfy.
[email protected]2ef3748f2010-10-19 17:33:28195 DCHECK_EQ(bucket_count_ + 1, ranges_.size());
196 DCHECK_EQ(0, ranges_[0]);
197 DCHECK_EQ(declared_min(), ranges_[1]);
198 DCHECK_EQ(declared_max(), ranges_[bucket_count_ - 1]);
199 DCHECK_EQ(kSampleType_MAX, ranges_[bucket_count_]);
initial.commitd7cae122008-07-26 21:49:38200 return true;
201}
202
203void Histogram::Initialize() {
204 sample_.Resize(*this);
[email protected]2ef3748f2010-10-19 17:33:28205 if (declared_min_ < 1)
initial.commitd7cae122008-07-26 21:49:38206 declared_min_ = 1;
[email protected]2ef3748f2010-10-19 17:33:28207 if (declared_max_ > kSampleType_MAX - 1)
initial.commitd7cae122008-07-26 21:49:38208 declared_max_ = kSampleType_MAX - 1;
[email protected]2ef3748f2010-10-19 17:33:28209 DCHECK_LE(declared_min_, declared_max_);
[email protected]70cc56e42010-04-29 22:39:55210 DCHECK_GT(bucket_count_, 1u);
initial.commitd7cae122008-07-26 21:49:38211 size_t maximal_bucket_count = declared_max_ - declared_min_ + 2;
[email protected]2ef3748f2010-10-19 17:33:28212 DCHECK_LE(bucket_count_, maximal_bucket_count);
213 DCHECK_EQ(0, ranges_[0]);
initial.commitd7cae122008-07-26 21:49:38214 ranges_[bucket_count_] = kSampleType_MAX;
215 InitializeBucketRange();
216 DCHECK(ValidateBucketRanges());
[email protected]e8829a192009-12-06 00:09:37217 StatisticsRecorder::Register(this);
initial.commitd7cae122008-07-26 21:49:38218}
219
220// Calculate what range of values are held in each bucket.
221// We have to be careful that we don't pick a ratio between starting points in
222// consecutive buckets that is sooo small, that the integer bounds are the same
223// (effectively making one bucket get no values). We need to avoid:
[email protected]93a41d72010-11-03 23:36:24224// ranges_[i] == ranges_[i + 1]
initial.commitd7cae122008-07-26 21:49:38225// To avoid that, we just do a fine-grained bucket width as far as we need to
226// until we get a ratio that moves us along at least 2 units at a time. From
227// that bucket onward we do use the exponential growth of buckets.
228void Histogram::InitializeBucketRange() {
229 double log_max = log(static_cast<double>(declared_max()));
230 double log_ratio;
231 double log_next;
232 size_t bucket_index = 1;
233 Sample current = declared_min();
234 SetBucketRange(bucket_index, current);
235 while (bucket_count() > ++bucket_index) {
236 double log_current;
237 log_current = log(static_cast<double>(current));
238 // Calculate the count'th root of the range.
239 log_ratio = (log_max - log_current) / (bucket_count() - bucket_index);
240 // See where the next bucket would start.
241 log_next = log_current + log_ratio;
242 int next;
243 next = static_cast<int>(floor(exp(log_next) + 0.5));
244 if (next > current)
245 current = next;
246 else
[email protected]55e57d42009-02-25 06:10:17247 ++current; // Just do a narrow bucket, and keep trying.
initial.commitd7cae122008-07-26 21:49:38248 SetBucketRange(bucket_index, current);
249 }
[email protected]93a41d72010-11-03 23:36:24250 ResetRangeChecksum();
initial.commitd7cae122008-07-26 21:49:38251
[email protected]2ef3748f2010-10-19 17:33:28252 DCHECK_EQ(bucket_count(), bucket_index);
initial.commitd7cae122008-07-26 21:49:38253}
254
255size_t Histogram::BucketIndex(Sample value) const {
256 // Use simple binary search. This is very general, but there are better
257 // approaches if we knew that the buckets were linearly distributed.
[email protected]2ef3748f2010-10-19 17:33:28258 DCHECK_LE(ranges(0), value);
259 DCHECK_GT(ranges(bucket_count()), value);
initial.commitd7cae122008-07-26 21:49:38260 size_t under = 0;
261 size_t over = bucket_count();
262 size_t mid;
263
264 do {
[email protected]2ef3748f2010-10-19 17:33:28265 DCHECK_GE(over, under);
initial.commitd7cae122008-07-26 21:49:38266 mid = (over + under)/2;
267 if (mid == under)
268 break;
269 if (ranges(mid) <= value)
270 under = mid;
271 else
272 over = mid;
273 } while (true);
274
[email protected]2ef3748f2010-10-19 17:33:28275 DCHECK_LE(ranges(mid), value);
276 DCHECK_GT(ranges(mid+1), value);
initial.commitd7cae122008-07-26 21:49:38277 return mid;
278}
279
280// Use the actual bucket widths (like a linear histogram) until the widths get
281// over some transition value, and then use that transition width. Exponentials
282// get so big so fast (and we don't expect to see a lot of entries in the large
283// buckets), so we need this to make it possible to see what is going on and
284// not have 0-graphical-height buckets.
285double Histogram::GetBucketSize(Count current, size_t i) const {
[email protected]2ef3748f2010-10-19 17:33:28286 DCHECK_GT(ranges(i + 1), ranges(i));
initial.commitd7cae122008-07-26 21:49:38287 static const double kTransitionWidth = 5;
288 double denominator = ranges(i + 1) - ranges(i);
289 if (denominator > kTransitionWidth)
290 denominator = kTransitionWidth; // Stop trying to normalize.
291 return current/denominator;
292}
293
[email protected]93a41d72010-11-03 23:36:24294void Histogram::ResetRangeChecksum() {
295 range_checksum_ = CalculateRangeChecksum();
296}
297
298bool Histogram::HasValidRangeChecksum() const {
299 return CalculateRangeChecksum() == range_checksum_;
300}
301
302Histogram::Sample Histogram::CalculateRangeChecksum() const {
303 DCHECK_EQ(ranges_.size(), bucket_count() + 1);
304 Sample checksum = 0;
305 for (size_t index = 0; index < bucket_count(); ++index) {
306 checksum += ranges(index);
307 }
308 return checksum;
309}
310
initial.commitd7cae122008-07-26 21:49:38311//------------------------------------------------------------------------------
312// The following two methods can be overridden to provide a thread safe
313// version of this class. The cost of locking is low... but an error in each
314// of these methods has minimal impact. For now, I'll leave this unlocked,
315// and I don't believe I can loose more than a count or two.
316// The vectors are NOT reallocated, so there is no risk of them moving around.
317
318// Update histogram data with new sample.
319void Histogram::Accumulate(Sample value, Count count, size_t index) {
320 // Note locking not done in this version!!!
321 sample_.Accumulate(value, count, index);
322}
323
324// Do a safe atomic snapshot of sample data.
325// This implementation assumes we are on a safe single thread.
326void Histogram::SnapshotSample(SampleSet* sample) const {
327 // Note locking not done in this version!!!
328 *sample = sample_;
329}
330
[email protected]835d7c82010-10-14 04:38:38331bool Histogram::HasConstructorArguments(Sample minimum,
332 Sample maximum,
[email protected]5d91c9e2010-07-28 17:25:28333 size_t bucket_count) {
334 return ((minimum == declared_min_) && (maximum == declared_max_) &&
335 (bucket_count == bucket_count_));
336}
337
[email protected]835d7c82010-10-14 04:38:38338bool Histogram::HasConstructorTimeDeltaArguments(TimeDelta minimum,
339 TimeDelta maximum,
[email protected]5d91c9e2010-07-28 17:25:28340 size_t bucket_count) {
341 return ((minimum.InMilliseconds() == declared_min_) &&
342 (maximum.InMilliseconds() == declared_max_) &&
343 (bucket_count == bucket_count_));
344}
345
initial.commitd7cae122008-07-26 21:49:38346//------------------------------------------------------------------------------
347// Accessor methods
348
349void Histogram::SetBucketRange(size_t i, Sample value) {
[email protected]2ef3748f2010-10-19 17:33:28350 DCHECK_GT(bucket_count_, i);
initial.commitd7cae122008-07-26 21:49:38351 ranges_[i] = value;
352}
353
354//------------------------------------------------------------------------------
355// Private methods
356
357double Histogram::GetPeakBucketSize(const SampleSet& snapshot) const {
358 double max = 0;
[email protected]55e57d42009-02-25 06:10:17359 for (size_t i = 0; i < bucket_count() ; ++i) {
initial.commitd7cae122008-07-26 21:49:38360 double current_size = GetBucketSize(snapshot.counts(i), i);
361 if (current_size > max)
362 max = current_size;
363 }
364 return max;
365}
366
367void Histogram::WriteAsciiHeader(const SampleSet& snapshot,
368 Count sample_count,
369 std::string* output) const {
[email protected]835d7c82010-10-14 04:38:38370 StringAppendF(output,
371 "Histogram: %s recorded %d samples",
372 histogram_name().c_str(),
373 sample_count);
initial.commitd7cae122008-07-26 21:49:38374 if (0 == sample_count) {
[email protected]70cc56e42010-04-29 22:39:55375 DCHECK_EQ(snapshot.sum(), 0);
initial.commitd7cae122008-07-26 21:49:38376 } else {
377 double average = static_cast<float>(snapshot.sum()) / sample_count;
378 double variance = static_cast<float>(snapshot.square_sum())/sample_count
379 - average * average;
380 double standard_deviation = sqrt(variance);
381
[email protected]835d7c82010-10-14 04:38:38382 StringAppendF(output,
383 ", average = %.1f, standard deviation = %.1f",
384 average, standard_deviation);
initial.commitd7cae122008-07-26 21:49:38385 }
[email protected]835d7c82010-10-14 04:38:38386 if (flags_ & ~kHexRangePrintingFlag)
387 StringAppendF(output, " (flags = 0x%x)", flags_ & ~kHexRangePrintingFlag);
initial.commitd7cae122008-07-26 21:49:38388}
389
390void Histogram::WriteAsciiBucketContext(const int64 past,
391 const Count current,
392 const int64 remaining,
393 const size_t i,
394 std::string* output) const {
395 double scaled_sum = (past + current + remaining) / 100.0;
396 WriteAsciiBucketValue(current, scaled_sum, output);
397 if (0 < i) {
398 double percentage = past / scaled_sum;
[email protected]835d7c82010-10-14 04:38:38399 StringAppendF(output, " {%3.1f%%}", percentage);
initial.commitd7cae122008-07-26 21:49:38400 }
401}
402
403const std::string Histogram::GetAsciiBucketRange(size_t i) const {
404 std::string result;
405 if (kHexRangePrintingFlag & flags_)
[email protected]835d7c82010-10-14 04:38:38406 StringAppendF(&result, "%#x", ranges(i));
initial.commitd7cae122008-07-26 21:49:38407 else
[email protected]835d7c82010-10-14 04:38:38408 StringAppendF(&result, "%d", ranges(i));
initial.commitd7cae122008-07-26 21:49:38409 return result;
410}
411
412void Histogram::WriteAsciiBucketValue(Count current, double scaled_sum,
413 std::string* output) const {
[email protected]835d7c82010-10-14 04:38:38414 StringAppendF(output, " (%d = %3.1f%%)", current, current/scaled_sum);
initial.commitd7cae122008-07-26 21:49:38415}
416
417void Histogram::WriteAsciiBucketGraph(double current_size, double max_size,
418 std::string* output) const {
419 const int k_line_length = 72; // Maximal horizontal width of graph.
420 int x_count = static_cast<int>(k_line_length * (current_size / max_size)
421 + 0.5);
422 int x_remainder = k_line_length - x_count;
423
424 while (0 < x_count--)
425 output->append("-");
426 output->append("O");
427 while (0 < x_remainder--)
428 output->append(" ");
429}
430
[email protected]55e57d42009-02-25 06:10:17431// static
432std::string Histogram::SerializeHistogramInfo(const Histogram& histogram,
433 const SampleSet& snapshot) {
[email protected]2ef3748f2010-10-19 17:33:28434 DCHECK_NE(NOT_VALID_IN_RENDERER, histogram.histogram_type());
[email protected]55e57d42009-02-25 06:10:17435
[email protected]e8829a192009-12-06 00:09:37436 Pickle pickle;
[email protected]55e57d42009-02-25 06:10:17437 pickle.WriteString(histogram.histogram_name());
438 pickle.WriteInt(histogram.declared_min());
439 pickle.WriteInt(histogram.declared_max());
440 pickle.WriteSize(histogram.bucket_count());
[email protected]93a41d72010-11-03 23:36:24441 pickle.WriteInt(histogram.range_checksum());
[email protected]55e57d42009-02-25 06:10:17442 pickle.WriteInt(histogram.histogram_type());
[email protected]1f4fc8e8c2010-01-02 00:46:41443 pickle.WriteInt(histogram.flags());
[email protected]55e57d42009-02-25 06:10:17444
445 snapshot.Serialize(&pickle);
446 return std::string(static_cast<const char*>(pickle.data()), pickle.size());
447}
448
449// static
[email protected]55e57d42009-02-25 06:10:17450bool Histogram::DeserializeHistogramInfo(const std::string& histogram_info) {
451 if (histogram_info.empty()) {
452 return false;
453 }
454
455 Pickle pickle(histogram_info.data(),
456 static_cast<int>(histogram_info.size()));
[email protected]93a41d72010-11-03 23:36:24457 std::string histogram_name;
[email protected]55e57d42009-02-25 06:10:17458 int declared_min;
459 int declared_max;
[email protected]93a41d72010-11-03 23:36:24460 size_t bucket_count;
461 int range_checksum;
[email protected]55e57d42009-02-25 06:10:17462 int histogram_type;
[email protected]2753b392009-12-28 06:59:52463 int pickle_flags;
[email protected]55e57d42009-02-25 06:10:17464 SampleSet sample;
465
[email protected]93a41d72010-11-03 23:36:24466 void* iter = NULL;
[email protected]55e57d42009-02-25 06:10:17467 if (!pickle.ReadString(&iter, &histogram_name) ||
468 !pickle.ReadInt(&iter, &declared_min) ||
469 !pickle.ReadInt(&iter, &declared_max) ||
470 !pickle.ReadSize(&iter, &bucket_count) ||
[email protected]93a41d72010-11-03 23:36:24471 !pickle.ReadInt(&iter, &range_checksum) ||
[email protected]55e57d42009-02-25 06:10:17472 !pickle.ReadInt(&iter, &histogram_type) ||
[email protected]2753b392009-12-28 06:59:52473 !pickle.ReadInt(&iter, &pickle_flags) ||
[email protected]55e57d42009-02-25 06:10:17474 !sample.Histogram::SampleSet::Deserialize(&iter, pickle)) {
[email protected]86440f52009-12-31 05:17:23475 LOG(ERROR) << "Pickle error decoding Histogram: " << histogram_name;
[email protected]55e57d42009-02-25 06:10:17476 return false;
477 }
[email protected]1f4fc8e8c2010-01-02 00:46:41478 DCHECK(pickle_flags & kIPCSerializationSourceFlag);
[email protected]86440f52009-12-31 05:17:23479 // Since these fields may have come from an untrusted renderer, do additional
480 // checks above and beyond those in Histogram::Initialize()
481 if (declared_max <= 0 || declared_min <= 0 || declared_max < declared_min ||
482 INT_MAX / sizeof(Count) <= bucket_count || bucket_count < 2) {
483 LOG(ERROR) << "Values error decoding Histogram: " << histogram_name;
484 return false;
485 }
486
[email protected]2753b392009-12-28 06:59:52487 Flags flags = static_cast<Flags>(pickle_flags & ~kIPCSerializationSourceFlag);
[email protected]55e57d42009-02-25 06:10:17488
[email protected]2ef3748f2010-10-19 17:33:28489 DCHECK_NE(NOT_VALID_IN_RENDERER, histogram_type);
[email protected]55e57d42009-02-25 06:10:17490
[email protected]e8829a192009-12-06 00:09:37491 scoped_refptr<Histogram> render_histogram(NULL);
492
[email protected]a764bf5e2010-06-02 21:31:44493 if (histogram_type == HISTOGRAM) {
[email protected]2753b392009-12-28 06:59:52494 render_histogram = Histogram::FactoryGet(
495 histogram_name, declared_min, declared_max, bucket_count, flags);
[email protected]e8829a192009-12-06 00:09:37496 } else if (histogram_type == LINEAR_HISTOGRAM) {
[email protected]2753b392009-12-28 06:59:52497 render_histogram = LinearHistogram::FactoryGet(
498 histogram_name, declared_min, declared_max, bucket_count, flags);
[email protected]e8829a192009-12-06 00:09:37499 } else if (histogram_type == BOOLEAN_HISTOGRAM) {
[email protected]2753b392009-12-28 06:59:52500 render_histogram = BooleanHistogram::FactoryGet(histogram_name, flags);
[email protected]e8829a192009-12-06 00:09:37501 } else {
[email protected]2ef3748f2010-10-19 17:33:28502 LOG(ERROR) << "Error Deserializing Histogram Unknown histogram_type: "
503 << histogram_type;
[email protected]e8829a192009-12-06 00:09:37504 return false;
[email protected]55e57d42009-02-25 06:10:17505 }
506
[email protected]2ef3748f2010-10-19 17:33:28507 DCHECK_EQ(render_histogram->declared_min(), declared_min);
508 DCHECK_EQ(render_histogram->declared_max(), declared_max);
509 DCHECK_EQ(render_histogram->bucket_count(), bucket_count);
[email protected]93a41d72010-11-03 23:36:24510 DCHECK_EQ(render_histogram->range_checksum(), range_checksum);
[email protected]2ef3748f2010-10-19 17:33:28511 DCHECK_EQ(render_histogram->histogram_type(), histogram_type);
[email protected]55e57d42009-02-25 06:10:17512
[email protected]e8829a192009-12-06 00:09:37513 if (render_histogram->flags() & kIPCSerializationSourceFlag) {
[email protected]2ef3748f2010-10-19 17:33:28514 DVLOG(1) << "Single process mode, histogram observed and not copied: "
515 << histogram_name;
[email protected]e8829a192009-12-06 00:09:37516 } else {
[email protected]2ef3748f2010-10-19 17:33:28517 DCHECK_EQ(flags & render_histogram->flags(), flags);
[email protected]e8829a192009-12-06 00:09:37518 render_histogram->AddSampleSet(sample);
[email protected]55e57d42009-02-25 06:10:17519 }
520
521 return true;
522}
523
initial.commitd7cae122008-07-26 21:49:38524//------------------------------------------------------------------------------
[email protected]93a41d72010-11-03 23:36:24525// Methods for the validating a sample and a related histogram.
526//------------------------------------------------------------------------------
527
528Histogram::Inconsistencies Histogram::FindCorruption(
529 const SampleSet& snapshot) const {
530 int inconsistencies = NO_INCONSISTENCIES;
531 Sample previous_range = -1; // Bottom range is always 0.
532 Sample checksum = 0;
533 int64 count = 0;
534 for (size_t index = 0; index < bucket_count(); ++index) {
535 count += snapshot.counts(index);
536 int new_range = ranges(index);
537 checksum += new_range;
538 if (previous_range >= new_range)
539 inconsistencies |= BUCKET_ORDER_ERROR;
540 previous_range = new_range;
541 }
542
543 if (checksum != range_checksum_)
544 inconsistencies |= RANGE_CHECKSUM_ERROR;
545
546 int64 delta64 = snapshot.redundant_count() - count;
547 if (delta64 != 0) {
548 int delta = static_cast<int>(delta64);
549 if (delta != delta64)
550 delta = INT_MAX; // Flag all giant errors as INT_MAX.
551 // Since snapshots of histograms are taken asynchronously relative to
552 // sampling (and snapped from different threads), it is pretty likely that
553 // we'll catch a redundant count that doesn't match the sample count. We
554 // allow for a certain amount of slop before flagging this as an
555 // inconsistency. Even with an inconsistency, we'll snapshot it again (for
556 // UMA in about a half hour, so we'll eventually get the data, if it was
557 // not the result of a corruption. If histograms show that 1 is "too tight"
558 // then we may try to use 2 or 3 for this slop value.
559 const int kCommonRaceBasedCountMismatch = 1;
560 if (delta > 0) {
561 UMA_HISTOGRAM_COUNTS("Histogram.InconsistentCountHigh", delta);
562 if (delta > kCommonRaceBasedCountMismatch)
563 inconsistencies |= COUNT_HIGH_ERROR;
564 } else {
565 DCHECK_GT(0, delta);
566 UMA_HISTOGRAM_COUNTS("Histogram.InconsistentCountLow", -delta);
567 if (-delta > kCommonRaceBasedCountMismatch)
568 inconsistencies |= COUNT_LOW_ERROR;
569 }
570 }
571 return static_cast<Inconsistencies>(inconsistencies);
572}
573
[email protected]7cf40912010-12-09 18:25:03574Histogram::ClassType Histogram::histogram_type() const {
575 return HISTOGRAM;
576}
577
578Histogram::Sample Histogram::ranges(size_t i) const {
579 return ranges_[i];
580}
581
582size_t Histogram::bucket_count() const {
583 return bucket_count_;
584}
585
[email protected]93a41d72010-11-03 23:36:24586//------------------------------------------------------------------------------
initial.commitd7cae122008-07-26 21:49:38587// Methods for the Histogram::SampleSet class
588//------------------------------------------------------------------------------
589
590Histogram::SampleSet::SampleSet()
591 : counts_(),
592 sum_(0),
[email protected]93a41d72010-11-03 23:36:24593 square_sum_(0),
594 redundant_count_(0) {
initial.commitd7cae122008-07-26 21:49:38595}
596
[email protected]d4799a32010-09-28 22:54:58597Histogram::SampleSet::~SampleSet() {
598}
599
initial.commitd7cae122008-07-26 21:49:38600void Histogram::SampleSet::Resize(const Histogram& histogram) {
601 counts_.resize(histogram.bucket_count(), 0);
602}
603
604void Histogram::SampleSet::CheckSize(const Histogram& histogram) const {
[email protected]2ef3748f2010-10-19 17:33:28605 DCHECK_EQ(histogram.bucket_count(), counts_.size());
initial.commitd7cae122008-07-26 21:49:38606}
607
608
609void Histogram::SampleSet::Accumulate(Sample value, Count count,
610 size_t index) {
611 DCHECK(count == 1 || count == -1);
612 counts_[index] += count;
613 sum_ += count * value;
614 square_sum_ += (count * value) * static_cast<int64>(value);
[email protected]93a41d72010-11-03 23:36:24615 redundant_count_ += count;
[email protected]2753b392009-12-28 06:59:52616 DCHECK_GE(counts_[index], 0);
617 DCHECK_GE(sum_, 0);
618 DCHECK_GE(square_sum_, 0);
[email protected]93a41d72010-11-03 23:36:24619 DCHECK_GE(redundant_count_, 0);
initial.commitd7cae122008-07-26 21:49:38620}
621
622Count Histogram::SampleSet::TotalCount() const {
623 Count total = 0;
624 for (Counts::const_iterator it = counts_.begin();
625 it != counts_.end();
[email protected]55e57d42009-02-25 06:10:17626 ++it) {
initial.commitd7cae122008-07-26 21:49:38627 total += *it;
628 }
629 return total;
630}
631
632void Histogram::SampleSet::Add(const SampleSet& other) {
[email protected]2ef3748f2010-10-19 17:33:28633 DCHECK_EQ(counts_.size(), other.counts_.size());
initial.commitd7cae122008-07-26 21:49:38634 sum_ += other.sum_;
635 square_sum_ += other.square_sum_;
[email protected]93a41d72010-11-03 23:36:24636 redundant_count_ += other.redundant_count_;
[email protected]55e57d42009-02-25 06:10:17637 for (size_t index = 0; index < counts_.size(); ++index)
initial.commitd7cae122008-07-26 21:49:38638 counts_[index] += other.counts_[index];
639}
640
641void Histogram::SampleSet::Subtract(const SampleSet& other) {
[email protected]2ef3748f2010-10-19 17:33:28642 DCHECK_EQ(counts_.size(), other.counts_.size());
initial.commitd7cae122008-07-26 21:49:38643 // Note: Race conditions in snapshotting a sum or square_sum may lead to
644 // (temporary) negative values when snapshots are later combined (and deltas
645 // calculated). As a result, we don't currently CHCEK() for positive values.
646 sum_ -= other.sum_;
647 square_sum_ -= other.square_sum_;
[email protected]93a41d72010-11-03 23:36:24648 redundant_count_ -= other.redundant_count_;
[email protected]55e57d42009-02-25 06:10:17649 for (size_t index = 0; index < counts_.size(); ++index) {
initial.commitd7cae122008-07-26 21:49:38650 counts_[index] -= other.counts_[index];
[email protected]2753b392009-12-28 06:59:52651 DCHECK_GE(counts_[index], 0);
initial.commitd7cae122008-07-26 21:49:38652 }
653}
654
[email protected]55e57d42009-02-25 06:10:17655bool Histogram::SampleSet::Serialize(Pickle* pickle) const {
656 pickle->WriteInt64(sum_);
657 pickle->WriteInt64(square_sum_);
[email protected]93a41d72010-11-03 23:36:24658 pickle->WriteInt64(redundant_count_);
[email protected]55e57d42009-02-25 06:10:17659 pickle->WriteSize(counts_.size());
660
661 for (size_t index = 0; index < counts_.size(); ++index) {
662 pickle->WriteInt(counts_[index]);
663 }
664
665 return true;
666}
667
668bool Histogram::SampleSet::Deserialize(void** iter, const Pickle& pickle) {
[email protected]2753b392009-12-28 06:59:52669 DCHECK_EQ(counts_.size(), 0u);
670 DCHECK_EQ(sum_, 0);
671 DCHECK_EQ(square_sum_, 0);
[email protected]93a41d72010-11-03 23:36:24672 DCHECK_EQ(redundant_count_, 0);
[email protected]55e57d42009-02-25 06:10:17673
674 size_t counts_size;
675
676 if (!pickle.ReadInt64(iter, &sum_) ||
677 !pickle.ReadInt64(iter, &square_sum_) ||
[email protected]93a41d72010-11-03 23:36:24678 !pickle.ReadInt64(iter, &redundant_count_) ||
[email protected]55e57d42009-02-25 06:10:17679 !pickle.ReadSize(iter, &counts_size)) {
680 return false;
681 }
682
[email protected]86440f52009-12-31 05:17:23683 if (counts_size == 0)
[email protected]55e57d42009-02-25 06:10:17684 return false;
685
[email protected]93a41d72010-11-03 23:36:24686 int count = 0;
[email protected]55e57d42009-02-25 06:10:17687 for (size_t index = 0; index < counts_size; ++index) {
[email protected]86440f52009-12-31 05:17:23688 int i;
689 if (!pickle.ReadInt(iter, &i))
[email protected]55e57d42009-02-25 06:10:17690 return false;
[email protected]86440f52009-12-31 05:17:23691 counts_.push_back(i);
[email protected]93a41d72010-11-03 23:36:24692 count += i;
[email protected]55e57d42009-02-25 06:10:17693 }
[email protected]93a41d72010-11-03 23:36:24694 DCHECK_EQ(count, redundant_count_);
695 return count == redundant_count_;
[email protected]55e57d42009-02-25 06:10:17696}
697
initial.commitd7cae122008-07-26 21:49:38698//------------------------------------------------------------------------------
699// LinearHistogram: This histogram uses a traditional set of evenly spaced
700// buckets.
701//------------------------------------------------------------------------------
702
[email protected]835d7c82010-10-14 04:38:38703scoped_refptr<Histogram> LinearHistogram::FactoryGet(const std::string& name,
704 Sample minimum,
705 Sample maximum,
706 size_t bucket_count,
707 Flags flags) {
[email protected]e8829a192009-12-06 00:09:37708 scoped_refptr<Histogram> histogram(NULL);
709
[email protected]2ef3748f2010-10-19 17:33:28710 if (minimum < 1)
[email protected]e8829a192009-12-06 00:09:37711 minimum = 1;
[email protected]2ef3748f2010-10-19 17:33:28712 if (maximum > kSampleType_MAX - 1)
[email protected]e8829a192009-12-06 00:09:37713 maximum = kSampleType_MAX - 1;
714
[email protected]f2bc0cb52010-06-25 15:55:15715 if (!StatisticsRecorder::FindHistogram(name, &histogram)) {
[email protected]e8829a192009-12-06 00:09:37716 histogram = new LinearHistogram(name, minimum, maximum, bucket_count);
[email protected]f2bc0cb52010-06-25 15:55:15717 StatisticsRecorder::FindHistogram(name, &histogram);
[email protected]e8829a192009-12-06 00:09:37718 }
719
[email protected]2ef3748f2010-10-19 17:33:28720 DCHECK_EQ(LINEAR_HISTOGRAM, histogram->histogram_type());
[email protected]e8829a192009-12-06 00:09:37721 DCHECK(histogram->HasConstructorArguments(minimum, maximum, bucket_count));
[email protected]2753b392009-12-28 06:59:52722 histogram->SetFlags(flags);
[email protected]e8829a192009-12-06 00:09:37723 return histogram;
724}
725
[email protected]46f89e142010-07-19 08:00:42726scoped_refptr<Histogram> LinearHistogram::FactoryTimeGet(
[email protected]835d7c82010-10-14 04:38:38727 const std::string& name,
728 TimeDelta minimum,
729 TimeDelta maximum,
730 size_t bucket_count,
731 Flags flags) {
[email protected]2753b392009-12-28 06:59:52732 return FactoryGet(name, minimum.InMilliseconds(), maximum.InMilliseconds(),
733 bucket_count, flags);
[email protected]e8829a192009-12-06 00:09:37734}
735
[email protected]d4799a32010-09-28 22:54:58736LinearHistogram::~LinearHistogram() {
737}
738
[email protected]835d7c82010-10-14 04:38:38739LinearHistogram::LinearHistogram(const std::string& name,
740 Sample minimum,
741 Sample maximum,
742 size_t bucket_count)
initial.commitd7cae122008-07-26 21:49:38743 : Histogram(name, minimum >= 1 ? minimum : 1, maximum, bucket_count) {
744 InitializeBucketRange();
745 DCHECK(ValidateBucketRanges());
746}
747
[email protected]e8829a192009-12-06 00:09:37748LinearHistogram::LinearHistogram(const std::string& name,
[email protected]835d7c82010-10-14 04:38:38749 TimeDelta minimum,
750 TimeDelta maximum,
751 size_t bucket_count)
initial.commitd7cae122008-07-26 21:49:38752 : Histogram(name, minimum >= TimeDelta::FromMilliseconds(1) ?
753 minimum : TimeDelta::FromMilliseconds(1),
754 maximum, bucket_count) {
755 // Do a "better" (different) job at init than a base classes did...
756 InitializeBucketRange();
757 DCHECK(ValidateBucketRanges());
758}
759
[email protected]5d91c9e2010-07-28 17:25:28760Histogram::ClassType LinearHistogram::histogram_type() const {
761 return LINEAR_HISTOGRAM;
762}
763
[email protected]5059e3a2009-01-14 16:01:03764void LinearHistogram::SetRangeDescriptions(
765 const DescriptionPair descriptions[]) {
initial.commitd7cae122008-07-26 21:49:38766 for (int i =0; descriptions[i].description; ++i) {
767 bucket_description_[descriptions[i].sample] = descriptions[i].description;
768 }
769}
770
771const std::string LinearHistogram::GetAsciiBucketRange(size_t i) const {
772 int range = ranges(i);
773 BucketDescriptionMap::const_iterator it = bucket_description_.find(range);
774 if (it == bucket_description_.end())
775 return Histogram::GetAsciiBucketRange(i);
776 return it->second;
777}
778
779bool LinearHistogram::PrintEmptyBucket(size_t index) const {
780 return bucket_description_.find(ranges(index)) == bucket_description_.end();
781}
782
783
784void LinearHistogram::InitializeBucketRange() {
[email protected]70cc56e42010-04-29 22:39:55785 DCHECK_GT(declared_min(), 0); // 0 is the underflow bucket here.
initial.commitd7cae122008-07-26 21:49:38786 double min = declared_min();
787 double max = declared_max();
788 size_t i;
[email protected]55e57d42009-02-25 06:10:17789 for (i = 1; i < bucket_count(); ++i) {
initial.commitd7cae122008-07-26 21:49:38790 double linear_range = (min * (bucket_count() -1 - i) + max * (i - 1)) /
791 (bucket_count() - 2);
792 SetBucketRange(i, static_cast<int> (linear_range + 0.5));
793 }
[email protected]93a41d72010-11-03 23:36:24794 ResetRangeChecksum();
initial.commitd7cae122008-07-26 21:49:38795}
796
initial.commitd7cae122008-07-26 21:49:38797double LinearHistogram::GetBucketSize(Count current, size_t i) const {
[email protected]2ef3748f2010-10-19 17:33:28798 DCHECK_GT(ranges(i + 1), ranges(i));
initial.commitd7cae122008-07-26 21:49:38799 // Adjacent buckets with different widths would have "surprisingly" many (few)
800 // samples in a histogram if we didn't normalize this way.
801 double denominator = ranges(i + 1) - ranges(i);
802 return current/denominator;
803}
804
805//------------------------------------------------------------------------------
[email protected]e8829a192009-12-06 00:09:37806// This section provides implementation for BooleanHistogram.
807//------------------------------------------------------------------------------
808
[email protected]2753b392009-12-28 06:59:52809scoped_refptr<Histogram> BooleanHistogram::FactoryGet(const std::string& name,
810 Flags flags) {
[email protected]e8829a192009-12-06 00:09:37811 scoped_refptr<Histogram> histogram(NULL);
812
[email protected]f2bc0cb52010-06-25 15:55:15813 if (!StatisticsRecorder::FindHistogram(name, &histogram)) {
[email protected]e8829a192009-12-06 00:09:37814 histogram = new BooleanHistogram(name);
[email protected]f2bc0cb52010-06-25 15:55:15815 StatisticsRecorder::FindHistogram(name, &histogram);
[email protected]e8829a192009-12-06 00:09:37816 }
817
[email protected]2ef3748f2010-10-19 17:33:28818 DCHECK_EQ(BOOLEAN_HISTOGRAM, histogram->histogram_type());
[email protected]2753b392009-12-28 06:59:52819 histogram->SetFlags(flags);
[email protected]e8829a192009-12-06 00:09:37820 return histogram;
821}
822
[email protected]5d91c9e2010-07-28 17:25:28823Histogram::ClassType BooleanHistogram::histogram_type() const {
824 return BOOLEAN_HISTOGRAM;
825}
826
827void BooleanHistogram::AddBoolean(bool value) {
828 Add(value ? 1 : 0);
829}
830
831BooleanHistogram::BooleanHistogram(const std::string& name)
832 : LinearHistogram(name, 1, 2, 3) {
833}
initial.commitd7cae122008-07-26 21:49:38834
835//------------------------------------------------------------------------------
[email protected]70cc56e42010-04-29 22:39:55836// CustomHistogram:
837//------------------------------------------------------------------------------
838
839scoped_refptr<Histogram> CustomHistogram::FactoryGet(
[email protected]835d7c82010-10-14 04:38:38840 const std::string& name,
[email protected]93a41d72010-11-03 23:36:24841 const std::vector<Sample>& custom_ranges,
[email protected]70cc56e42010-04-29 22:39:55842 Flags flags) {
843 scoped_refptr<Histogram> histogram(NULL);
844
845 // Remove the duplicates in the custom ranges array.
846 std::vector<int> ranges = custom_ranges;
847 ranges.push_back(0); // Ensure we have a zero value.
848 std::sort(ranges.begin(), ranges.end());
849 ranges.erase(std::unique(ranges.begin(), ranges.end()), ranges.end());
850 if (ranges.size() <= 1) {
851 DCHECK(false);
852 // Note that we pushed a 0 in above, so for defensive code....
853 ranges.push_back(1); // Put in some data so we can index to [1].
854 }
855
856 DCHECK_LT(ranges.back(), kSampleType_MAX);
857
[email protected]f2bc0cb52010-06-25 15:55:15858 if (!StatisticsRecorder::FindHistogram(name, &histogram)) {
[email protected]70cc56e42010-04-29 22:39:55859 histogram = new CustomHistogram(name, ranges);
[email protected]f2bc0cb52010-06-25 15:55:15860 StatisticsRecorder::FindHistogram(name, &histogram);
[email protected]70cc56e42010-04-29 22:39:55861 }
862
863 DCHECK_EQ(histogram->histogram_type(), CUSTOM_HISTOGRAM);
864 DCHECK(histogram->HasConstructorArguments(ranges[1], ranges.back(),
865 ranges.size()));
866 histogram->SetFlags(flags);
867 return histogram;
868}
869
[email protected]5d91c9e2010-07-28 17:25:28870Histogram::ClassType CustomHistogram::histogram_type() const {
871 return CUSTOM_HISTOGRAM;
872}
873
[email protected]70cc56e42010-04-29 22:39:55874CustomHistogram::CustomHistogram(const std::string& name,
[email protected]93a41d72010-11-03 23:36:24875 const std::vector<Sample>& custom_ranges)
[email protected]70cc56e42010-04-29 22:39:55876 : Histogram(name, custom_ranges[1], custom_ranges.back(),
877 custom_ranges.size()) {
878 DCHECK_GT(custom_ranges.size(), 1u);
879 DCHECK_EQ(custom_ranges[0], 0);
880 ranges_vector_ = &custom_ranges;
881 InitializeBucketRange();
882 ranges_vector_ = NULL;
883 DCHECK(ValidateBucketRanges());
884}
885
886void CustomHistogram::InitializeBucketRange() {
[email protected]2ef3748f2010-10-19 17:33:28887 DCHECK_LE(ranges_vector_->size(), bucket_count());
[email protected]835d7c82010-10-14 04:38:38888 for (size_t index = 0; index < ranges_vector_->size(); ++index)
[email protected]70cc56e42010-04-29 22:39:55889 SetBucketRange(index, (*ranges_vector_)[index]);
[email protected]93a41d72010-11-03 23:36:24890 ResetRangeChecksum();
[email protected]70cc56e42010-04-29 22:39:55891}
892
893double CustomHistogram::GetBucketSize(Count current, size_t i) const {
894 return 1;
895}
896
897//------------------------------------------------------------------------------
initial.commitd7cae122008-07-26 21:49:38898// The next section handles global (central) support for all histograms, as well
899// as startup/teardown of this service.
900//------------------------------------------------------------------------------
901
902// This singleton instance should be started during the single threaded portion
903// of main(), and hence it is not thread safe. It initializes globals to
904// provide support for all future calls.
905StatisticsRecorder::StatisticsRecorder() {
906 DCHECK(!histograms_);
[email protected]d14425542010-12-23 14:40:10907 if (lock_ == NULL) {
908 // This will leak on purpose. It's the only way to make sure we won't race
909 // against the static uninitialization of the module while one of our
910 // static methods relying on the lock get called at an inappropriate time
911 // during the termination phase. Since it's a static data member, we will
912 // leak one per process, which would be similar to the instance allocated
913 // during static initialization and released only on process termination.
[email protected]bc581a682011-01-01 23:16:20914 lock_ = new base::Lock;
[email protected]d14425542010-12-23 14:40:10915 }
[email protected]bc581a682011-01-01 23:16:20916 base::AutoLock auto_lock(*lock_);
initial.commitd7cae122008-07-26 21:49:38917 histograms_ = new HistogramMap;
918}
919
920StatisticsRecorder::~StatisticsRecorder() {
[email protected]d14425542010-12-23 14:40:10921 DCHECK(histograms_ && lock_);
initial.commitd7cae122008-07-26 21:49:38922
923 if (dump_on_exit_) {
924 std::string output;
925 WriteGraph("", &output);
[email protected]89fb65a2010-10-18 21:53:00926 LOG(INFO) << output;
initial.commitd7cae122008-07-26 21:49:38927 }
initial.commitd7cae122008-07-26 21:49:38928 // Clean up.
[email protected]d14425542010-12-23 14:40:10929 HistogramMap* histograms = NULL;
930 {
[email protected]bc581a682011-01-01 23:16:20931 base::AutoLock auto_lock(*lock_);
[email protected]d14425542010-12-23 14:40:10932 histograms = histograms_;
933 histograms_ = NULL;
934 }
935 delete histograms;
936 // We don't delete lock_ on purpose to avoid having to properly protect
937 // against it going away after we checked for NULL in the static methods.
initial.commitd7cae122008-07-26 21:49:38938}
939
940// static
[email protected]d14425542010-12-23 14:40:10941bool StatisticsRecorder::IsActive() {
942 if (lock_ == NULL)
943 return false;
[email protected]bc581a682011-01-01 23:16:20944 base::AutoLock auto_lock(*lock_);
initial.commitd7cae122008-07-26 21:49:38945 return NULL != histograms_;
946}
947
[email protected]e8829a192009-12-06 00:09:37948// Note: We can't accept a ref_ptr to |histogram| because we *might* not keep a
949// reference, and we are called while in the Histogram constructor. In that
950// scenario, a ref_ptr would have incremented the ref count when the histogram
951// was passed to us, decremented it when we returned, and the instance would be
952// destroyed before assignment (when value was returned by new).
initial.commitd7cae122008-07-26 21:49:38953// static
[email protected]e8829a192009-12-06 00:09:37954void StatisticsRecorder::Register(Histogram* histogram) {
[email protected]d14425542010-12-23 14:40:10955 if (lock_ == NULL)
956 return;
[email protected]bc581a682011-01-01 23:16:20957 base::AutoLock auto_lock(*lock_);
initial.commitd7cae122008-07-26 21:49:38958 if (!histograms_)
959 return;
[email protected]55e57d42009-02-25 06:10:17960 const std::string name = histogram->histogram_name();
[email protected]cc82864b2010-08-17 19:46:51961 // Avoid overwriting a previous registration.
962 if (histograms_->end() == histograms_->find(name))
963 (*histograms_)[name] = histogram;
initial.commitd7cae122008-07-26 21:49:38964}
965
966// static
967void StatisticsRecorder::WriteHTMLGraph(const std::string& query,
968 std::string* output) {
[email protected]d14425542010-12-23 14:40:10969 if (!IsActive())
initial.commitd7cae122008-07-26 21:49:38970 return;
971 output->append("<html><head><title>About Histograms");
972 if (!query.empty())
973 output->append(" - " + query);
974 output->append("</title>"
975 // We'd like the following no-cache... but it doesn't work.
976 // "<META HTTP-EQUIV=\"Pragma\" CONTENT=\"no-cache\">"
977 "</head><body>");
978
979 Histograms snapshot;
980 GetSnapshot(query, &snapshot);
981 for (Histograms::iterator it = snapshot.begin();
982 it != snapshot.end();
[email protected]55e57d42009-02-25 06:10:17983 ++it) {
initial.commitd7cae122008-07-26 21:49:38984 (*it)->WriteHTMLGraph(output);
985 output->append("<br><hr><br>");
986 }
987 output->append("</body></html>");
988}
989
990// static
991void StatisticsRecorder::WriteGraph(const std::string& query,
[email protected]55e57d42009-02-25 06:10:17992 std::string* output) {
[email protected]d14425542010-12-23 14:40:10993 if (!IsActive())
initial.commitd7cae122008-07-26 21:49:38994 return;
[email protected]835d7c82010-10-14 04:38:38995 if (query.length())
996 StringAppendF(output, "Collections of histograms for %s\n", query.c_str());
997 else
initial.commitd7cae122008-07-26 21:49:38998 output->append("Collections of all histograms\n");
999
1000 Histograms snapshot;
1001 GetSnapshot(query, &snapshot);
1002 for (Histograms::iterator it = snapshot.begin();
1003 it != snapshot.end();
[email protected]55e57d42009-02-25 06:10:171004 ++it) {
initial.commitd7cae122008-07-26 21:49:381005 (*it)->WriteAscii(true, "\n", output);
1006 output->append("\n");
1007 }
1008}
1009
1010// static
1011void StatisticsRecorder::GetHistograms(Histograms* output) {
[email protected]d14425542010-12-23 14:40:101012 if (lock_ == NULL)
initial.commitd7cae122008-07-26 21:49:381013 return;
[email protected]bc581a682011-01-01 23:16:201014 base::AutoLock auto_lock(*lock_);
[email protected]d14425542010-12-23 14:40:101015 if (!histograms_)
1016 return;
initial.commitd7cae122008-07-26 21:49:381017 for (HistogramMap::iterator it = histograms_->begin();
1018 histograms_->end() != it;
[email protected]55e57d42009-02-25 06:10:171019 ++it) {
[email protected]2ef3748f2010-10-19 17:33:281020 DCHECK_EQ(it->first, it->second->histogram_name());
initial.commitd7cae122008-07-26 21:49:381021 output->push_back(it->second);
1022 }
1023}
1024
[email protected]e8829a192009-12-06 00:09:371025bool StatisticsRecorder::FindHistogram(const std::string& name,
1026 scoped_refptr<Histogram>* histogram) {
[email protected]d14425542010-12-23 14:40:101027 if (lock_ == NULL)
[email protected]e8829a192009-12-06 00:09:371028 return false;
[email protected]bc581a682011-01-01 23:16:201029 base::AutoLock auto_lock(*lock_);
[email protected]d14425542010-12-23 14:40:101030 if (!histograms_)
1031 return false;
[email protected]e8829a192009-12-06 00:09:371032 HistogramMap::iterator it = histograms_->find(name);
1033 if (histograms_->end() == it)
1034 return false;
1035 *histogram = it->second;
1036 return true;
[email protected]55e57d42009-02-25 06:10:171037}
1038
initial.commitd7cae122008-07-26 21:49:381039// private static
1040void StatisticsRecorder::GetSnapshot(const std::string& query,
1041 Histograms* snapshot) {
[email protected]d14425542010-12-23 14:40:101042 if (lock_ == NULL)
1043 return;
[email protected]bc581a682011-01-01 23:16:201044 base::AutoLock auto_lock(*lock_);
[email protected]d14425542010-12-23 14:40:101045 if (!histograms_)
1046 return;
initial.commitd7cae122008-07-26 21:49:381047 for (HistogramMap::iterator it = histograms_->begin();
1048 histograms_->end() != it;
[email protected]55e57d42009-02-25 06:10:171049 ++it) {
initial.commitd7cae122008-07-26 21:49:381050 if (it->first.find(query) != std::string::npos)
1051 snapshot->push_back(it->second);
1052 }
1053}
1054
1055// static
1056StatisticsRecorder::HistogramMap* StatisticsRecorder::histograms_ = NULL;
1057// static
[email protected]bc581a682011-01-01 23:16:201058base::Lock* StatisticsRecorder::lock_ = NULL;
initial.commitd7cae122008-07-26 21:49:381059// static
1060bool StatisticsRecorder::dump_on_exit_ = false;
[email protected]835d7c82010-10-14 04:38:381061
1062} // namespace base