Added getHours() and getString() that automatically chooses resolution

This commit is contained in:
Matthew Ellison
2019-02-09 12:56:18 -05:00
parent 674b62b671
commit 6753a98502

View File

@@ -4,7 +4,10 @@
#Modified: 2-1-19 #Modified: 2-1-19
#This is a class that is used to time program run times #This is a class that is used to time program run times
import time import time
import math
class Stopwatch: class Stopwatch:
#Initialize the class and all the variables you will need #Initialize the class and all the variables you will need
@@ -76,3 +79,62 @@ class Stopwatch:
return minute return minute
else: else:
return (minute / 60000000000) 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