1 // Copyright 2011 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 NINJA_METRICS_H_ 16 #define NINJA_METRICS_H_ 17 18 #include <string> 19 #include <vector> 20 21 #include "util.h" // For int64_t. 22 23 /// The Metrics module is used for the debug mode that dumps timing stats of 24 /// various actions. To use, see METRIC_RECORD below. 25 26 /// A single metrics we're tracking, like "depfile load time". 27 struct Metric { 28 std::string name; 29 /// Number of times we've hit the code path. 30 int count; 31 /// Total time (in micros) we've spent on the code path. 32 int64_t sum; 33 }; 34 35 36 /// A scoped object for recording a metric across the body of a function. 37 /// Used by the METRIC_RECORD macro. 38 struct ScopedMetric { 39 explicit ScopedMetric(Metric* metric); 40 ~ScopedMetric(); 41 42 private: 43 Metric* metric_; 44 /// Timestamp when the measurement started. 45 /// Value is platform-dependent. 46 int64_t start_; 47 }; 48 49 /// The singleton that stores metrics and prints the report. 50 struct Metrics { 51 Metric* NewMetric(const std::string& name); 52 53 /// Print a summary report to stdout. 54 void Report(); 55 56 private: 57 std::vector<Metric*> metrics_; 58 }; 59 60 /// Get the current time as relative to some epoch. 61 /// Epoch varies between platforms; only useful for measuring elapsed time. 62 int64_t GetTimeMillis(); 63 64 /// A simple stopwatch which returns the time 65 /// in seconds since Restart() was called. 66 struct Stopwatch { 67 public: StopwatchStopwatch68 Stopwatch() : started_(0) {} 69 70 /// Seconds since Restart() call. ElapsedStopwatch71 double Elapsed() const { 72 return 1e-6 * static_cast<double>(Now() - started_); 73 } 74 RestartStopwatch75 void Restart() { started_ = Now(); } 76 77 private: 78 uint64_t started_; 79 uint64_t Now() const; 80 }; 81 82 /// The primary interface to metrics. Use METRIC_RECORD("foobar") at the top 83 /// of a function to get timing stats recorded for each call of the function. 84 #define METRIC_RECORD(name) \ 85 static Metric* metrics_h_metric = \ 86 g_metrics ? g_metrics->NewMetric(name) : NULL; \ 87 ScopedMetric metrics_h_scoped(metrics_h_metric); 88 89 extern Metrics* g_metrics; 90 91 #endif // NINJA_METRICS_H_ 92