mirror of
https://bitbucket.org/Mattrixwv/pytutorial.git
synced 2025-12-06 18:23:57 -05:00
Created a Stopwatch class and test scripts
This commit is contained in:
33
Stopwatch.py
Normal file
33
Stopwatch.py
Normal 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
30
testStopwatch.py
Normal 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:
|
||||||
|
|
||||||
|
"""
|
||||||
Reference in New Issue
Block a user