1 #ifndef CPPROFILER_UTILS_PERF_HELPER_HH 2 #define CPPROFILER_UTILS_PERF_HELPER_HH 3 4 #include <iostream> 5 #include <chrono> 6 7 #include <unordered_map> 8 9 #include "debug.hh" 10 11 namespace detail 12 { 13 using namespace std::chrono; 14 15 struct PerfInstance 16 { 17 using TimePoint = time_point<high_resolution_clock>; 18 long long current = 0; 19 TimePoint begin; 20 }; 21 22 class PerformanceHelper 23 { 24 using TimePoint = time_point<high_resolution_clock>; 25 26 private: 27 high_resolution_clock m_hrClock; 28 TimePoint m_begin; 29 const char *m_message; 30 31 std::unordered_map<const char *, PerfInstance> maps; 32 33 public: begin(const char * msg)34 void begin(const char *msg) 35 { 36 m_message = msg; 37 m_begin = m_hrClock.now(); 38 } 39 accumulate(const char * msg)40 void accumulate(const char *msg) 41 { 42 maps[msg].begin = m_hrClock.now(); 43 } 44 end(const char * msg)45 void end(const char *msg) 46 { 47 auto now = m_hrClock.now(); 48 auto duration_ns = 49 duration_cast<nanoseconds>(now - maps[msg].begin).count(); 50 maps[msg].current += duration_ns; 51 maps[msg].begin = now; 52 } 53 total(const char * msg)54 void total(const char *msg) 55 { 56 auto dur = maps[msg].current; 57 std::cout << "Duration(" << msg << "): " << dur / 1000000 << "ms" 58 << " (" << dur << "ns)\n"; 59 } 60 end()61 void end() 62 { 63 auto duration_ms = 64 duration_cast<milliseconds>(m_hrClock.now() - m_begin).count(); 65 auto duration_ns = 66 duration_cast<nanoseconds>(m_hrClock.now() - m_begin).count(); 67 ::cpprofiler::print("Duration({}): {}ms ({}ns)", m_message, duration_ms, duration_ns); 68 } 69 }; 70 71 } // namespace detail 72 73 namespace perf_helper 74 { 75 76 using namespace std::chrono; 77 78 struct Timer 79 { 80 using TimePoint = time_point<high_resolution_clock>; 81 high_resolution_clock m_hrClock; 82 TimePoint m_begin; 83 beginperf_helper::Timer84 void begin() 85 { 86 m_begin = m_hrClock.now(); 87 } 88 endperf_helper::Timer89 int64_t end() 90 { 91 int64_t ms = 92 duration_cast<milliseconds>(m_hrClock.now() - m_begin).count(); 93 return ms; 94 } 95 }; 96 97 } // namespace perf_helper 98 99 extern detail::PerformanceHelper perfHelper; 100 101 #endif