How to write a function to get the time spent in each function in Python?

PythonServer Side ProgrammingProgramming

To measure time time of a program's execution, either use time.clock() or time.time() functions. The python docs state that this function should be used for benchmarking purposes. You can place these function calls around the function you want to benchmark and use them to get the time spent in a 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 the output −

Time elapsed:  0.0009403145040156798

You can also use the timeit module to get proper statistical analysis of a code snippet's execution time.  It runs the snippet multiple times and then it tells you how long the shortest run took. You can use it as follows:

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 the output −

[2.0640320777893066, 2.0876040458679199, 2.0520210266113281]


raja
Published on 08-Jan-2018 07:36:17
Advertisements