So, my aim is to break from the while loop after 1 seconds. I made 3 separate functions with the same logic:
max_time = 1
def func1():
start_time = time.monotonic()
elapsed_time = 0
i = 0
while elapsed_time < max_time:
try:
i+=1
elapsed_time = time.monotonic() - start_time
except KeyboardInterrupt:
print('\nKeyboard Interrupt :(')
break
return i
def func2():
start_time = time.monotonic()
i = 0
while (time.monotonic() - start_time) < max_time:
try:
i+=1
except KeyboardInterrupt:
print('\nKeyboard Interrupt :(')
break
return i
def func3():
start_time = time.monotonic()
time_limit = time.monotonic() + max_time
i = 0
while time.monotonic() < time_limit:
try:
i+=1
except KeyboardInterrupt:
print('\nKeyboard Interrupt :(')
break
return i
I ran all three functions. Based on the value of i returned by the 3 functions is func1 < func2 < func3, which implies that func1 takes less amount of time while func3 takes the most amount of time to run. The difference between func1 and func2 is very minimal.
I'm wondering why func3 takes so much time when its basically the same logic as fun1 and fun2.
I believe your confusion here comes from a misunderstanding of what the return value (the i
value) of your functions are. It is not the amount of time required to execute each function.
func1
, func2
, and func3
all take the same amount of time to complete. Note that your logic, as you've said above, is basically to continue iterating until 1 second has passed.
What the return value (the i
value) is calculating is actually the number of iterations each function can run in 1 second. This means that each loop in func3
takes less time to complete because it can run more loops in one second.
This makes sense because func1
and func2
both do an arithmetic calculation in each iteration (in the try
block of func1
and in the while loop check in func2
), whereas func3
performs that arithmetic calculation outside of the while loop and therefore saves some computing time per iteration.
What you're essentially calculating here is the time it takes to perform an arithmetic calculation in python.