stats_counters.cc revision 731df977c0511bca2206b5f333555b1205ff1f43
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.
4
5#include "base/metrics/stats_counters.h"
6
7namespace base {
8
9StatsCounter::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);
14}
15
16StatsCounter::~StatsCounter() {
17}
18
19void StatsCounter::Set(int value) {
20  int* loc = GetPtr();
21  if (loc)
22    *loc = value;
23}
24
25void StatsCounter::Add(int value) {
26  int* loc = GetPtr();
27  if (loc)
28    (*loc) += value;
29}
30
31StatsCounter::StatsCounter()
32    : counter_id_(-1) {
33}
34
35int* StatsCounter::GetPtr() {
36  StatsTable* table = StatsTable::current();
37  if (!table)
38    return NULL;
39
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;
49      }
50    }
51  }
52
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());
56
57  // counter_id_ was zero, which means the table is full.
58  return NULL;
59}
60
61
62StatsCounterTimer::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);
66}
67
68StatsCounterTimer::~StatsCounterTimer() {
69}
70
71void StatsCounterTimer::Start() {
72  if (!Enabled())
73    return;
74  start_time_ = TimeTicks::Now();
75  stop_time_ = TimeTicks();
76}
77
78// Stop the timer and record the results.
79void StatsCounterTimer::Stop() {
80  if (!Enabled() || !Running())
81    return;
82  stop_time_ = TimeTicks::Now();
83  Record();
84}
85
86// Returns true if the timer is running.
87bool StatsCounterTimer::Running() {
88  return Enabled() && !start_time_.is_null() && stop_time_.is_null();
89}
90
91// Accept a TimeDelta to increment.
92void StatsCounterTimer::AddTime(TimeDelta time) {
93  Add(static_cast<int>(time.InMilliseconds()));
94}
95
96void StatsCounterTimer::Record() {
97  AddTime(stop_time_ - start_time_);
98}
99
100
101StatsRate::StatsRate(const std::string& name)
102    : StatsCounterTimer(name),
103      counter_(name),
104      largest_add_(std::string(" ").append(name).append("MAX")) {
105}
106
107StatsRate::~StatsRate() {
108}
109
110void StatsRate::Add(int value) {
111  counter_.Increment();
112  StatsCounterTimer::Add(value);
113  if (value > largest_add_.value())
114    largest_add_.Set(value);
115}
116
117}  // namespace base
118