1 // Copyright 2015 Google Inc. All rights reserved
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at
6 //
7 // http://www.apache.org/licenses/LICENSE-2.0
8 //
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS IS" BASIS,
11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 // See the License for the specific language governing permissions and
13 // limitations under the License.
14
15 // +build ignore
16
17 #include "stats.h"
18
19 #include <algorithm>
20 #include <mutex>
21 #include <vector>
22
23 #include "flags.h"
24 #include "log.h"
25 #include "stringprintf.h"
26 #include "thread_local.h"
27 #include "timeutil.h"
28
29 namespace {
30
31 mutex g_mu;
32 vector<Stats*>* g_stats;
33 DEFINE_THREAD_LOCAL(double, g_start_time);
34
35 } // namespace
36
Stats(const char * name)37 Stats::Stats(const char* name) : name_(name), elapsed_(0), cnt_(0) {
38 unique_lock<mutex> lock(g_mu);
39 if (g_stats == NULL)
40 g_stats = new vector<Stats*>;
41 g_stats->push_back(this);
42 }
43
DumpTop() const44 void Stats::DumpTop() const {
45 unique_lock<mutex> lock(mu_);
46 if (detailed_.size() > 0) {
47 vector<pair<string, double>> v(detailed_.begin(), detailed_.end());
48 sort(
49 v.begin(), v.end(),
50 [](const pair<string, double> a, const pair<string, double> b) -> bool {
51 return a.second > b.second;
52 });
53 for (unsigned int i = 0; i < 10 && i < v.size(); i++) {
54 LOG_STAT(" %5.3f %s", v[i].first.c_str(), v[i].second);
55 }
56 }
57 }
58
String() const59 string Stats::String() const {
60 unique_lock<mutex> lock(mu_);
61 return StringPrintf("%s: %f / %d", name_, elapsed_, cnt_);
62 }
63
Start()64 void Stats::Start() {
65 CHECK(!TLS_REF(g_start_time));
66 TLS_REF(g_start_time) = GetTime();
67 unique_lock<mutex> lock(mu_);
68 cnt_++;
69 }
70
End(const char * msg)71 double Stats::End(const char* msg) {
72 CHECK(TLS_REF(g_start_time));
73 double e = GetTime() - TLS_REF(g_start_time);
74 TLS_REF(g_start_time) = 0;
75 unique_lock<mutex> lock(mu_);
76 elapsed_ += e;
77 if (msg != 0) {
78 detailed_[string(msg)] += e;
79 }
80 return e;
81 }
82
ScopedStatsRecorder(Stats * st,const char * msg)83 ScopedStatsRecorder::ScopedStatsRecorder(Stats* st, const char* msg)
84 : st_(st), msg_(msg) {
85 if (!g_flags.enable_stat_logs)
86 return;
87 st_->Start();
88 }
89
~ScopedStatsRecorder()90 ScopedStatsRecorder::~ScopedStatsRecorder() {
91 if (!g_flags.enable_stat_logs)
92 return;
93 double e = st_->End(msg_);
94 if (msg_ && e > 3.0) {
95 LOG_STAT("slow %s (%f): %s", st_->name_, e, msg_);
96 }
97 }
98
ReportAllStats()99 void ReportAllStats() {
100 if (!g_stats)
101 return;
102 for (Stats* st : *g_stats) {
103 LOG_STAT("%s", st->String().c_str());
104 st->DumpTop();
105 }
106 delete g_stats;
107 }
108