1 /*!
2  * Copyright by Contributors 2017-2019
3  */
4 #pragma once
5 #include <xgboost/logging.h>
6 #include <chrono>
7 #include <iostream>
8 #include <map>
9 #include <string>
10 #include <utility>
11 #include <vector>
12 
13 namespace xgboost {
14 namespace common {
15 
16 struct Timer {
17   using ClockT = std::chrono::high_resolution_clock;
18   using TimePointT = std::chrono::high_resolution_clock::time_point;
19   using DurationT = std::chrono::high_resolution_clock::duration;
20   using SecondsT = std::chrono::duration<double>;
21 
22   TimePointT start;
23   DurationT elapsed;
TimerTimer24   Timer() { Reset(); }
ResetTimer25   void Reset() {
26     elapsed = DurationT::zero();
27     Start();
28   }
StartTimer29   void Start() { start = ClockT::now(); }
StopTimer30   void Stop() { elapsed += ClockT::now() - start; }
ElapsedSecondsTimer31   double ElapsedSeconds() const { return SecondsT(elapsed).count(); }
PrintElapsedTimer32   void PrintElapsed(std::string label) {
33     char buffer[255];
34     snprintf(buffer, sizeof(buffer), "%s:\t %fs", label.c_str(),
35              SecondsT(elapsed).count());
36     LOG(CONSOLE) << buffer;
37     Reset();
38   }
39 };
40 
41 /**
42  * \struct  Monitor
43  *
44  * \brief Timing utility used to measure total method execution time over the
45  * lifetime of the containing object.
46  */
47 struct Monitor {
48  private:
49   struct Statistics {
50     Timer timer;
51     size_t count{0};
52     uint64_t nvtx_id;
53   };
54 
55   // from left to right, <name <count, elapsed>>
56   using StatMap = std::map<std::string, std::pair<size_t, size_t>>;
57 
58   std::string label_ = "";
59   std::map<std::string, Statistics> statistics_map_;
60   Timer self_timer_;
61 
62   void PrintStatistics(StatMap const& statistics) const;
63 
64  public:
MonitorMonitor65   Monitor() { self_timer_.Start(); }
66   /*\brief Print statistics info during destruction.
67    *
68    * Please note that this may not work, as with distributed frameworks like Dask, the
69    * model is pickled to other workers, and the global parameters like `global_verbosity_`
70    * are not included in the pickle.
71    */
~MonitorMonitor72   ~Monitor() {
73     this->Print();
74     self_timer_.Stop();
75   }
76 
77   /*! \brief Print all the statistics. */
78   void Print() const;
79 
InitMonitor80   void Init(std::string label) { this->label_ = label; }
81   void Start(const std::string &name);
82   void Stop(const std::string &name);
83 };
84 }  // namespace common
85 }  // namespace xgboost
86