Python Program to Measure the Elapsed Time in Python

To understand this example, you should have the knowledge of the following Python programming topics:


Example 1: Using time module

import time

# Save timestamp
start = time.time()

print(23*2.3)

# Save timestamp
end = time.time()

print(end - start)

Output

52.9
3.600120544433594e-05

In order to calculate the time elapsed in executing a code, the time module can be used.

  • Save the timestamp at the beginning of the code start using the time() function.
  • Save the timestamp at the end of the code end.
  • Find the difference between the end and start, which gives the execution time.

The execution time depends on the system.

Note: The time.time() function from the time module returns the current time in seconds.


Example 2: Using timeit module

from timeit import default_timer as timer

start = timer()

print(23*2.3)

end = timer()
print(end - start)

Output

52.9
6.355400000000039e-05

Similar to Example 1, we use the timer() method from the timeit module.

timeit provides the most accurate results.

Note: The timer() function also returns the current time in seconds.


Also Read:

Did you find this article helpful?

Our premium learning platform, created with over a decade of experience and thousands of feedbacks.

Learn and improve your coding skills like never before.

Try Programiz PRO
  • Interactive Courses
  • Certificates
  • AI Help
  • 2000+ Challenges