Home > Mobile >  How can I turn an execution time-counter into one or two functions?
How can I turn an execution time-counter into one or two functions?

Time:05-09

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())

CodePudding user response:

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))

  • Related