1/*
2 * libjingle
3 * Copyright 2013, Google Inc.
4 *
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions are met:
7 *
8 *  1. Redistributions of source code must retain the above copyright notice,
9 *     this list of conditions and the following disclaimer.
10 *  2. Redistributions in binary form must reproduce the above copyright notice,
11 *     this list of conditions and the following disclaimer in the documentation
12 *     and/or other materials provided with the distribution.
13 *  3. The name of the author may not be used to endorse or promote products
14 *     derived from this software without specific prior written permission.
15 *
16 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
17 * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
18 * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
19 * EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
20 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
21 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
22 * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
23 * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
24 * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
25 * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
26 */
27
28#include "talk/base/profiler.h"
29
30#include <math.h>
31
32#include "talk/base/timeutils.h"
33
34namespace {
35
36// When written to an ostream, FormattedTime chooses an appropriate scale and
37// suffix for a time value given in seconds.
38class FormattedTime {
39 public:
40  explicit FormattedTime(double t) : time_(t) {}
41  double time() const { return time_; }
42 private:
43  double time_;
44};
45
46std::ostream& operator<<(std::ostream& stream, const FormattedTime& time) {
47  if (time.time() < 1.0) {
48    stream << (time.time() * 1000.0) << "ms";
49  } else {
50    stream << time.time() << 's';
51  }
52  return stream;
53}
54
55}  // namespace
56
57namespace talk_base {
58
59ProfilerEvent::ProfilerEvent()
60    : total_time_(0.0),
61      mean_(0.0),
62      sum_of_squared_differences_(0.0),
63      start_count_(0),
64      event_count_(0) {
65}
66
67void ProfilerEvent::Start() {
68  if (start_count_ == 0) {
69    current_start_time_ = TimeNanos();
70  }
71  ++start_count_;
72}
73
74void ProfilerEvent::Stop() {
75  uint64 stop_time = TimeNanos();
76  --start_count_;
77  ASSERT(start_count_ >= 0);
78  if (start_count_ == 0) {
79    double elapsed = static_cast<double>(stop_time - current_start_time_) /
80        kNumNanosecsPerSec;
81    total_time_ += elapsed;
82    if (event_count_ == 0) {
83      minimum_ = maximum_ = elapsed;
84    } else {
85      minimum_ = _min(minimum_, elapsed);
86      maximum_ = _max(maximum_, elapsed);
87    }
88    // Online variance and mean algorithm: http://en.wikipedia.org/wiki/
89    // Algorithms_for_calculating_variance#Online_algorithm
90    ++event_count_;
91    double delta = elapsed - mean_;
92    mean_ = mean_ + delta / event_count_;
93    sum_of_squared_differences_ += delta * (elapsed - mean_);
94  }
95}
96
97double ProfilerEvent::standard_deviation() const {
98    if (event_count_ <= 1) return 0.0;
99    return sqrt(sum_of_squared_differences_ / (event_count_ - 1.0));
100}
101
102Profiler* Profiler::Instance() {
103  LIBJINGLE_DEFINE_STATIC_LOCAL(Profiler, instance, ());
104  return &instance;
105}
106
107void Profiler::StartEvent(const std::string& event_name) {
108  events_[event_name].Start();
109}
110
111void Profiler::StopEvent(const std::string& event_name) {
112  events_[event_name].Stop();
113}
114
115void Profiler::ReportToLog(const char* file, int line,
116                           LoggingSeverity severity_to_use,
117                           const std::string& event_prefix) {
118  if (!LogMessage::Loggable(severity_to_use)) {
119    return;
120  }
121  { // Output first line.
122    LogMessage msg(file, line, severity_to_use);
123    msg.stream() << "=== Profile report ";
124    if (event_prefix.empty()) {
125      msg.stream() << "(prefix: '" << event_prefix << "') ";
126    }
127    msg.stream() << "===";
128  }
129  typedef std::map<std::string, ProfilerEvent>::const_iterator iterator;
130  for (iterator it = events_.begin(); it != events_.end(); ++it) {
131    if (event_prefix.empty() || it->first.find(event_prefix) == 0) {
132      LogMessage(file, line, severity_to_use).stream()
133          << it->first << " count=" << it->second.event_count()
134          << " total=" << FormattedTime(it->second.total_time())
135          << " mean=" << FormattedTime(it->second.mean())
136          << " min=" << FormattedTime(it->second.minimum())
137          << " max=" << FormattedTime(it->second.maximum())
138          << " sd=" << it->second.standard_deviation();
139    }
140  }
141  LogMessage(file, line, severity_to_use).stream()
142      << "=== End profile report ===";
143}
144
145void Profiler::ReportAllToLog(const char* file, int line,
146                           LoggingSeverity severity_to_use) {
147  ReportToLog(file, line, severity_to_use, "");
148}
149
150const ProfilerEvent* Profiler::GetEvent(const std::string& event_name) const {
151  std::map<std::string, ProfilerEvent>::const_iterator it =
152      events_.find(event_name);
153  return (it == events_.end()) ? NULL : &it->second;
154}
155
156bool Profiler::Clear() {
157  bool result = true;
158  // Clear all events that aren't started.
159  std::map<std::string, ProfilerEvent>::iterator it = events_.begin();
160  while (it != events_.end()) {
161    if (it->second.is_started()) {
162      ++it;  // Can't clear started events.
163      result = false;
164    } else {
165      events_.erase(it++);
166    }
167  }
168  return result;
169}
170
171}  // namespace talk_base
172