Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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 :

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading