How to use Python datetime Module to measure elapsed time in Python In Python
we can also use Python datetime module, we can also record time and find the execution time of a block of code. The process is same as using time.time(), measuring start and end time and then calculating the difference.
Example: How to measure elapsed time using datetime.datetime.now()
Python3
# importing the module from datetime import datetime # sample function for testing def print_square(x): return x * * 2 # record start time (in datetime format) start = datetime.now() # calls the function print_square( 3 ) # record rnd time (in datetime format) end = datetime.now() # print elapsed time in microseconds print ( "Elapsed" , (end - start).total_seconds() * 10 * * 6 , "µs" ) |
Output:
Elapsed 12.0 µs
How to measure elapsed time in Python?
In Python, we can measure the elapsed time on executing a code segment or a Python script using some built-in Python modules. Here we will cover the usage of time, timeit and datetime module.
Contact Us