mrobertini1239 mrobertini1239 - 2 months ago 18
Python Question

Stopwatch implementing python

I got this code for an assignment:

from stop_watch import StopWatch
size = 1000000
stopWatch = StopWatch()
sum = 0
for i in range(1, size + 1):
sum += i

stopWatch.stop()
print("The loop time is", stopWatch.get_elapsed_time(), "milliseconds")


I have to create a class which generates a stopwatch and this is my code:

import time

class StopWatch:
def __init__(self):
pass

def start(self):
self.start = time.time()
return self.start

def stop(self):
self.stop = time.time()
return self.stop

def get_elapsed_time(self):
print(str(self.stop-self.start))


I get this error:

File "week33.py", line 10, in <module>
print("The loop time is", stopWatch.get_elapsed_time(), "milliseconds")
File "/Users/Marinkton/Desktop/stop_watch.py", line 16, in get_elapsed_time
print(str(self.stop-self.start))
TypeError: unsupported operand type(s) for -: 'float' and 'method'





What am I doing wrong? I could not discover a mistake.

Answer

You can't name your functions and your properties the same thing. When you do self.stop = time.time(), you overwrite the function stop.

You need to change the name of the internal fields.

import time

class StopWatch:
    def __init__(self):
        self.start_time = 0
        self.stop_time = 0

    def start(self):
        self.start_time = time.time()
        return self.start_time

    def stop(self):
        self.stop_time = time.time()
        return self.stop_time

    def get_elapsed_time(self):
        print(str(self.stop_time - self.start_time))

PS: You're never calling start in your code.