1 /******************************************************************************* 2 * Copyright 2021 Intel Corporation 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License. 15 *******************************************************************************/ 16 17 #ifndef UTILS_TIMER_HPP 18 #define UTILS_TIMER_HPP 19 20 #include <map> 21 #include <string> 22 23 #define TIME_FUNC(func, res, name) \ 24 do { \ 25 auto &t = res->timer_map.get_timer(name); \ 26 t.start(); \ 27 func; \ 28 t.stop(); \ 29 } while (0) 30 31 // Designated timer to calculate time spent on reference computations 32 #define TIME_REF(func) TIME_FUNC(func, res, timer::timer_t::ref_timer) 33 34 namespace timer { 35 36 struct timer_t { 37 enum mode_t { min = 0, avg = 1, max = 2, sum = 3, n_modes }; 38 timer_ttimer::timer_t39 timer_t() { reset(); } 40 41 void reset(); /** fully reset the measurements */ 42 43 void start(); /** restart timer */ 44 void stop(int add_times = 1); /** stop timer & update statistics */ 45 stamptimer::timer_t46 void stamp(int add_times = 1) { stop(add_times); } 47 timestimer::timer_t48 int times() const { return times_; } 49 total_mstimer::timer_t50 double total_ms() const { return ms_[avg]; } 51 mstimer::timer_t52 double ms(mode_t mode = min) const { 53 if (!times()) return 0; // nothing to report 54 return ms_[mode] / (mode == avg ? times() : 1); 55 } 56 sectimer::timer_t57 double sec(mode_t mode = min) const { return ms(mode) / 1e3; } 58 tickstimer::timer_t59 unsigned long long ticks(mode_t mode = min) const { 60 if (!times()) return 0; // nothing to report 61 return ticks_[mode] / (mode == avg ? times() : 1); 62 } 63 64 timer_t &operator=(const timer_t &rhs); 65 66 int times_; 67 unsigned long long ticks_[n_modes], ticks_start_; 68 double ms_[n_modes], ms_start_; 69 70 // Section with timer fixed timer names for ease of use 71 static const std::string perf_timer; 72 static const std::string ref_timer; 73 }; 74 75 struct timer_map_t { 76 timer_t &get_timer(const std::string &name); 77 78 timer_t &perf_timer(); 79 80 std::map<std::string, timer_t> timers; 81 }; 82 83 } // namespace timer 84 85 #endif 86