Python StopWatch milliseconds

(Stopwatch) Design a class named StopWatch. The class contains:
■ The private data fields startTime and endTime with get methods.
■ A constructor that initializes startTime with the current time.
■ A method named start() that resets the startTime to the current time.
■ A method named stop() that sets the endTime to the current time.
■ A method named getElapsedTime() that returns the elapsed time for the stop watch in milliseconds.
Write a test program that measures the execution time of adding numbers from 1 to 1,000,000.

from datetime import datetime
Import time
class StopWatch():
    now = datetime.now()
   
def __init__(self,  endTime = 0, startTime = datetime.now()):
       
self.__startTime = startTime
       
self.__endTime = endTime

   
def getStart(self):
       
return self.__startTime
   
def getEnd(self):
        
return self.__endTime
   
def start(self):
       
self.__startTime = round(time.time()*1000)
       
return self.__startTime
   
def stop(self):
       
self.__endTime = round(time.time()*1000)
       
return self.__endTime

   
def getElapsedTime(self):
        etime = StopWatch.getEnd(
self) - StopWatch.getStart(self)
       
return etime
   
def loop(self):
        count =
0
       
for i in range(1000000):
            count +=
1
       
return count

def main():
    s = StopWatch()
   
print('Start time: ', s.start())
   
print(s.loop())
   
print('Stop time: ', s.stop())
   
print('The execution time of adding numbers from 1 to 1,000,000 is: ', s.getElapsedTime())

main()


SOLUTION:

Start time:  830213
1000000
Stop time:  982221

The execution time of adding numbers from 1 to 1,000,000 is:  152008  milliseconds!

Коментари

Популарни постови са овог блога

Python Fan functions

Python Accounting