Created a Stopwatch class and test scripts

This commit is contained in:
2019-01-24 12:31:42 -05:00
parent 1653336389
commit 5dcd104717
2 changed files with 63 additions and 0 deletions

33
Stopwatch.py Normal file
View File

@@ -0,0 +1,33 @@
#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
def start(self):
self.started = True
self.finished = False
self.timeStarted = time.perf_counter()
def stop(self):
#If the stopwatch has been started then you record the stopping time
if(self.started):
self.timeStopped = time.perf_counter()
self.finished = True
#Otherwise just ignore the function call
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
elif(self.started):
return "The stopwatch was started, but never stopped"
else:
return "The stopwatch was never started"

30
testStopwatch.py Normal file
View File

@@ -0,0 +1,30 @@
#~/Programs/Python/pyTutorial/testStopwatch.py
#Matthew Ellison
# Created: 1-24-19
#Modified: 1-24-19
#This is a simple test script for the Stopwatch class
from Stopwatch import Stopwatch
timer = Stopwatch()
print("Trying to print the time before it has been started:")
print(str(timer.getTime()))
timer.stop()
print("Trying to print the time after stop was called, but before start was")
print(str(timer.getTime()))
timer.start()
print("Trying to print the time after it was started but before it was stopped:")
print(str(timer.getTime()))
cnt = 0
print("Entering loop:")
while(cnt < 1000):
print(cnt)
cnt = cnt + 1
print("Exiting loop")
timer.stop()
print("Trying to print time after it was finished")
print(str(timer.getTime()))
"""Results:
"""