Line data Source code
1 : /** 2 : * @file timing.hpp 3 : * @brief Timing functions 4 : * 5 : * @details Contains the definition and implementation of a Clock structure for timing purposes. 6 : * 7 : * @author Volkan Kumtepeli 8 : * @author Becky Perriment 9 : * @date 01 Mar 2022 10 : */ 11 : 12 : #pragma once 13 : 14 : #include <ctime> 15 : #include <iostream> 16 : #include <cmath> 17 : #include <chrono> 18 : 19 : namespace dtwc { 20 : 21 : /** 22 : * @brief Structure representing a high-resolution clock. 23 : * 24 : * Clock structure to measure time intervals with high resolution. 25 : */ 26 : struct Clock 27 : { 28 : std::chrono::time_point<std::chrono::high_resolution_clock> tstart{ std::chrono::high_resolution_clock::now() }; 29 7 : Clock() = default; 30 4 : auto now() const { return std::chrono::high_resolution_clock::now(); } 31 6 : auto start() const { return tstart; } 32 : 33 : /** 34 : * @brief Calculates the duration since the clock started. 35 : * @return Duration in seconds. 36 : */ 37 3 : double duration() const 38 : { 39 3 : std::chrono::duration<double> elapsed_seconds = now() - start(); 40 6 : return elapsed_seconds.count(); 41 : } 42 : 43 : /** 44 : * @brief Prints the duration in minutes and seconds format. 45 : * @param ofs Output stream to print the duration. 46 : * @param duration Duration in seconds. 47 : */ 48 1 : static void print_duration(std::ostream &ofs, double duration) 49 : { 50 1 : ofs << std::floor(duration / 60) << ":" 51 1 : << duration - std::floor(duration / 60) * 60 52 1 : << " min:sec\n"; 53 1 : } 54 : }; 55 : 56 : /** 57 : * @brief Overloads the << operator for the Clock structure. 58 : * @param ofs Output stream. 59 : * @param clk Clock instance. 60 : * @return Reference to the output stream. 61 : */ 62 1 : inline std::ostream &operator<<(std::ostream &ofs, const Clock &clk) 63 : { 64 1 : const auto duration = clk.duration(); 65 1 : ofs << std::floor(duration / 60) << ":" 66 1 : << duration - std::floor(duration / 60) * 60 67 1 : << " min:sec"; 68 : 69 1 : return ofs; 70 : } 71 : } // namespace dtwc