From 3c99ab2eb06e3b9043ac96b6c34b8336df0eb39c Mon Sep 17 00:00:00 2001 From: Mattrixwv Date: Wed, 8 Jul 2020 16:39:25 -0400 Subject: [PATCH] Added a function that returns a string when passed a duration in nanoseconds. Helpful for easy conversion in some benchmarks --- Stopwatch.hpp | 44 +++++++++++++++++++++++++++++++++++++++++++- 1 file changed, 43 insertions(+), 1 deletion(-) diff --git a/Stopwatch.hpp b/Stopwatch.hpp index df835a8..eec923f 100644 --- a/Stopwatch.hpp +++ b/Stopwatch.hpp @@ -147,7 +147,7 @@ public: //Returns a string with the time at best resolution std::string getStr(){ //Setup the variables - double tempTime = getTime(NANOSECOND); //Holds the + double tempTime = getTime(NANOSECOND); //Holds the time that we are manipulating std::stringstream timeStr; //Decide what time resolution would be best. Looking for the format of XXX.XXX @@ -192,6 +192,48 @@ public: endTime = startTime = std::chrono::high_resolution_clock::time_point(); //Set the times with a blank time } friend std::ostream& operator<<(std::ostream& out, Stopwatch& timer); + + static std::string getStr(double nanoseconds){ + //Setup the variables + double tempTime = nanoseconds; //Holds the time that we are manipulating + std::stringstream timeStr; + + //Decide what time resolution would be best. Looking for the format of XXX.XXX + int timeRes = NANOSECOND; + for(timeRes = MICROSECOND;(timeRes < DEFAULT) && (tempTime >= 1000);++timeRes){ + tempTime /= 1000; + } + --timeRes; //Take this variable back down to the right place. It has to go one too far to trigger the loop stop + + //Check if the resolution is seconds and if there are more than 120 seconds + if((timeRes == SECOND) && (tempTime >= 120)){ + ++timeRes; + tempTime /= 60; + } + //Check if the resolution is minutes and if there are more than 120 minutes + else if((timeRes == MINUTE) && (tempTime >= 120)){ + ++timeRes; + tempTime /= 60; + } + + //Put the number in the string + timeStr << std::fixed << std::setprecision(3) << tempTime << ' '; + + //From the timeRes variable decide what word should go on the end of the string + switch(timeRes){ + case HOUR: timeStr << "hours"; break; + case MINUTE: timeStr << "minutes"; break; + case SECOND: timeStr << "seconds"; break; + case MILLISECOND: timeStr << "milliseconds"; break; + case MICROSECOND: timeStr << "microseconds"; break; + case NANOSECOND: timeStr << "nanoseconds"; break; + case DEFAULT: timeStr << "time"; break; + default: throw invalidTimeResolution(); //This should never be hit with this code, but it's good to have all the bases covered + } + + //Return the string + return timeStr.str(); + } }; //end class Stopwatch std::ostream& operator<<(std::ostream& out, Stopwatch& timer){ out << timer.getStr();