From 6753a9850249215cd8e8560d15e9a27c62011134 Mon Sep 17 00:00:00 2001 From: Matthew Ellison Date: Sat, 9 Feb 2019 12:56:18 -0500 Subject: [PATCH] Added getHours() and getString() that automatically chooses resolution --- Stopwatch.py | 62 ++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 62 insertions(+) diff --git a/Stopwatch.py b/Stopwatch.py index 2a803a0..17a3c03 100644 --- a/Stopwatch.py +++ b/Stopwatch.py @@ -4,7 +4,10 @@ #Modified: 2-1-19 #This is a class that is used to time program run times + import time +import math + class Stopwatch: #Initialize the class and all the variables you will need @@ -76,3 +79,62 @@ class Stopwatch: return minute else: return (minute / 60000000000) + + #Returns the result of getTime() in terms of hours + def getHours(self): + hour = self.getTime() + if(hour < 0): + return hour + else: + return (hour / 3600000000000) + + #Returns a string with the result of getTime() at the appropriate resolution + def getString(self): + #Get the time + time = self.getTime() + + #Divide by 1000 until you reach an appropriate resolution or run out of types of seconds + resCnt = 0 + while((time >= 1000) and (resCnt < 3)): + time /= 1000 + resCnt += 1 + + #If the resolution counter reached 3 we may need to change to minutes or hours + #Check if seconds is low enough resolution + if(time >= 1000): + #If not, change it to minutes + time /= 60 + resCnt += 1 + + #Check if minutes is low enough resolution + if(time >= 1000): + #If not, change it to hours + time /= 60 + resCnt += 1 + + #Create a string with the number at ___.___ resolution + timeString = "" + #If nanoseconds was used we don't need the fractional part + if(resCnt == 0): + timeString = str(time) + ' ' + else: + timeString = "{0}.{1:03d} ".format(math.floor(time), round((time % 1) * 1000)) + + #Determine the resolution of the number and add the appropriate word + if(resCnt == 0): + timeString += "nanoseconds" + elif(resCnt == 1): + timeString += "microseconds" + elif(resCnt == 2): + timeString += "milliseconds" + elif(resCnt == 3): + timeString += "seconds" + elif(resCnt == 4): + timeString += "minutes" + elif(resCnt == 5): + timeString += "hours" + else: + timeString = "error" + + #Return the string + return timeString