mirror of
https://bitbucket.org/Mattrixwv/pytutorial.git
synced 2025-12-06 10:13:58 -05:00
Added functions for different resolutions of time
This commit is contained in:
44
Stopwatch.py
44
Stopwatch.py
@@ -10,24 +10,58 @@ class Stopwatch:
|
||||
self.started = False #This variable holds true after the start function has been called
|
||||
self.finished = False #This variable holds true after the start and stop functions have been called
|
||||
|
||||
#Save the time at this point. Simulates starting a stopwatch
|
||||
def start(self):
|
||||
self.started = True
|
||||
self.finished = False
|
||||
self.timeStarted = time.perf_counter()
|
||||
self.timeStarted = time.perf_counter_ns()
|
||||
|
||||
#Save the time at this point. Simulates stopping a stopwatch
|
||||
def stop(self):
|
||||
#If the stopwatch has been started then you record the stopping time
|
||||
if(self.started):
|
||||
self.timeStopped = time.perf_counter()
|
||||
self.timeStopped = time.perf_counter_ns()
|
||||
self.finished = True
|
||||
#Otherwise just ignore the function call
|
||||
|
||||
#Returns the difference between two times, usually start and stop times, but can be start time and now
|
||||
#Simulates looking at the stopwatch; it can still be running when you look at it
|
||||
def getTime(self):
|
||||
#If the start and stop function have been called then calculate the time between the calls
|
||||
if(self.finished):
|
||||
return (self.timeStopped - self.timeStarted)
|
||||
#Otherwise return messages about what is wrong
|
||||
#If start was called but not stop calculate the time between start and now. Simulates looking at the watch while still running
|
||||
elif(self.started):
|
||||
return "The stopwatch was started, but never stopped"
|
||||
return (time.perf_counter_ns() - self.timeStarted)
|
||||
#If start was never called return a negative number. In this context time can never be negative
|
||||
else:
|
||||
return "The stopwatch was never started"
|
||||
return -1
|
||||
|
||||
#Return a specific resolution of time. This is done as a floating point number
|
||||
#Returns the result of getTime() in terms of seconds
|
||||
def getSeconds(self):
|
||||
second = self.getTime()
|
||||
if(second < 0):
|
||||
return second
|
||||
else:
|
||||
return (second / 1000000000)
|
||||
|
||||
#Returns the result of getTime() in terms of milliseconds
|
||||
def getMilliseconds(self):
|
||||
milli = self.getTime()
|
||||
if(milli < 0):
|
||||
return milli
|
||||
else:
|
||||
return (milli / 1000000)
|
||||
|
||||
#Returns the result of getTime() in terms of microseconds
|
||||
def getMicroseconds(self):
|
||||
micro = self.getTime()
|
||||
if(micro < 0):
|
||||
return micro
|
||||
else:
|
||||
return (micro / 1000)
|
||||
|
||||
#Returns the result of getTime() in terms of nanoseconds
|
||||
def getNanoseconds(self):
|
||||
return self.getTime()
|
||||
|
||||
Reference in New Issue
Block a user