How do I get the time spent on each function in Python?

Python Methods and Functions

To measure the execution time of a program, use the time.clock () or time.time () functions. The Python docs state that this feature should be used for testing purposes. You can wrap these function calls around the function you want to compare and use them to get the time spent on the function. 


Example

 import time t0 = time.clock () print ("Hello") t1 = time.clock () - t0 print ("Time elapsed:", t1 - t0) # CPU seconds elapsed (floating point) 



Output

This will give output &



 Time elapsed: 0.0009403145040156798 

You can also use the timeit module to correctly statistically analyze the execution time of a piece of code. It runs the snippet multiple times and then reports how long the shortest cycle took. You can use it like this:






Example

 def f (x): return x * x import timeit timeit.repeat ("for x in range (100): f (x)", "from __main__ import f", number = 100000) 



Output

This will give output &

 [2.0640320777893066, 2.0876040458679199, 2.0520210266113281] 







Get Solution for free from DataCamp guru