'How can I turn an execution time-counter into one or two functions?
I use this code often:
import time
start = time.time()
for i in range(1000):
i ** 2000
end = time.time() - start
print(end)
This gives the time a block of code took to execute.
I'm trying to turn that process into one or two functions but I'm having a hard time conceptualizing it.
Something like this but it always gives 0.0:
def start_timer():
return time.time()
def stop_timer():
return time.time() - start_timer()
start_timer()
for i in range(1000):
i ** 2000
print(stop_timer())
Solution 1:[1]
start_timer returns the starting time, You need to save it inside a variable.
import time
def start_timer():
return time.time()
def stop_timer(t):
return time.time()-t
t = start_timer()
for i in range(1000):
i ** 2000
print(stop_timer(t))
# IF you need to use this again then simple do this
t = start_timer()
for a in range(10000):
a**100
print(stop_timer(t))
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Sharim Iqbal |
