Files
PyTutorials/Stopwatch.py

68 lines
2.4 KiB
Python

#This is a class that is used to time program run times
import time
class Stopwatch:
#Initialize the class and all the variables you will need
def __init__(self):
self.timeStarted = 0.0 #This variable holds the time that the start function was called
self.timeStopped = 0.0 #This variable holds the time that the stop function was called
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_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_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)
#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 (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 -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()