WebKit Roll 77375:77377.
[chromium-blink-merge.git] / base / metrics / stats_counters.cc
blob958f0483fe00b10a39ac790bafe9fea157e75570
1 // Copyright (c) 2010 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
5 #include "base/metrics/stats_counters.h"
7 namespace base {
9 StatsCounter::StatsCounter(const std::string& name)
10 : counter_id_(-1) {
11 // We prepend the name with 'c:' to indicate that it is a counter.
12 name_ = "c:";
13 name_.append(name);
16 StatsCounter::~StatsCounter() {
19 void StatsCounter::Set(int value) {
20 int* loc = GetPtr();
21 if (loc)
22 *loc = value;
25 void StatsCounter::Add(int value) {
26 int* loc = GetPtr();
27 if (loc)
28 (*loc) += value;
31 StatsCounter::StatsCounter()
32 : counter_id_(-1) {
35 int* StatsCounter::GetPtr() {
36 StatsTable* table = StatsTable::current();
37 if (!table)
38 return NULL;
40 // If counter_id_ is -1, then we haven't looked it up yet.
41 if (counter_id_ == -1) {
42 counter_id_ = table->FindCounter(name_);
43 if (table->GetSlot() == 0) {
44 if (!table->RegisterThread("")) {
45 // There is no room for this thread. This thread
46 // cannot use counters.
47 counter_id_ = 0;
48 return NULL;
53 // If counter_id_ is > 0, then we have a valid counter.
54 if (counter_id_ > 0)
55 return table->GetLocation(counter_id_, table->GetSlot());
57 // counter_id_ was zero, which means the table is full.
58 return NULL;
62 StatsCounterTimer::StatsCounterTimer(const std::string& name) {
63 // we prepend the name with 't:' to indicate that it is a timer.
64 name_ = "t:";
65 name_.append(name);
68 StatsCounterTimer::~StatsCounterTimer() {
71 void StatsCounterTimer::Start() {
72 if (!Enabled())
73 return;
74 start_time_ = TimeTicks::Now();
75 stop_time_ = TimeTicks();
78 // Stop the timer and record the results.
79 void StatsCounterTimer::Stop() {
80 if (!Enabled() || !Running())
81 return;
82 stop_time_ = TimeTicks::Now();
83 Record();
86 // Returns true if the timer is running.
87 bool StatsCounterTimer::Running() {
88 return Enabled() && !start_time_.is_null() && stop_time_.is_null();
91 // Accept a TimeDelta to increment.
92 void StatsCounterTimer::AddTime(TimeDelta time) {
93 Add(static_cast<int>(time.InMilliseconds()));
96 void StatsCounterTimer::Record() {
97 AddTime(stop_time_ - start_time_);
101 StatsRate::StatsRate(const std::string& name)
102 : StatsCounterTimer(name),
103 counter_(name),
104 largest_add_(std::string(" ").append(name).append("MAX")) {
107 StatsRate::~StatsRate() {
110 void StatsRate::Add(int value) {
111 counter_.Increment();
112 StatsCounterTimer::Add(value);
113 if (value > largest_add_.value())
114 largest_add_.Set(value);
117 } // namespace base