blob: 25f6e5beccacfe27970e853655872872b82fc725 [file] [log] [blame]
Shinichiro Hamaji0d8e79b2015-06-30 03:29:35 +09001// 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#ifndef STATS_H_
16#define STATS_H_
17
Shinichiro Hamaji8380fb82016-02-26 16:51:50 +090018#include <mutex>
Shinichiro Hamaji0d8e79b2015-06-30 03:29:35 +090019#include <string>
Dan Willemsen2d552db2018-01-30 16:55:33 -080020#include <unordered_map>
Shinichiro Hamaji0d8e79b2015-06-30 03:29:35 +090021
22using namespace std;
23
24class Stats {
25 public:
26 explicit Stats(const char* name);
27
Dan Willemsen2d552db2018-01-30 16:55:33 -080028 void DumpTop() const;
Shinichiro Hamaji0d8e79b2015-06-30 03:29:35 +090029 string String() const;
30
31 private:
32 void Start();
Dan Willemsen2d552db2018-01-30 16:55:33 -080033 double End(const char* msg);
Shinichiro Hamaji0d8e79b2015-06-30 03:29:35 +090034
35 friend class ScopedStatsRecorder;
36
37 const char* name_;
Shinichiro Hamaji0d8e79b2015-06-30 03:29:35 +090038 double elapsed_;
Shinichiro Hamaji8c8358d2015-06-30 17:08:00 +090039 int cnt_;
Shinichiro Hamaji8380fb82016-02-26 16:51:50 +090040 mutable mutex mu_;
Dan Willemsen2d552db2018-01-30 16:55:33 -080041 unordered_map<string, double> detailed_;
Shinichiro Hamaji0d8e79b2015-06-30 03:29:35 +090042};
43
44class ScopedStatsRecorder {
45 public:
Shinichiro Hamajib123fe52015-06-30 16:32:56 +090046 explicit ScopedStatsRecorder(Stats* st, const char* msg = 0);
Shinichiro Hamaji0d8e79b2015-06-30 03:29:35 +090047 ~ScopedStatsRecorder();
48
49 private:
50 Stats* st_;
Shinichiro Hamajib123fe52015-06-30 16:32:56 +090051 const char* msg_;
Shinichiro Hamaji0d8e79b2015-06-30 03:29:35 +090052};
53
54void ReportAllStats();
55
Dan Willemsen3ce083f2017-10-11 22:17:48 -070056#define COLLECT_STATS(name) \
57 static Stats stats(name); \
Shinichiro Hamaji0d8e79b2015-06-30 03:29:35 +090058 ScopedStatsRecorder ssr(&stats)
59
Dan Willemsen3ce083f2017-10-11 22:17:48 -070060#define COLLECT_STATS_WITH_SLOW_REPORT(name, msg) \
61 static Stats stats(name); \
Shinichiro Hamajib123fe52015-06-30 16:32:56 +090062 ScopedStatsRecorder ssr(&stats, msg)
63
Shinichiro Hamaji0d8e79b2015-06-30 03:29:35 +090064#endif // STATS_H_