Python time module

Time in Python is easy to implement and it can be used anywhere in a program to measure the execution time. By using timers we can get the exact time and we can improve the program where it takes too long. The time module provides the methods in order to profile a program. 

Example 1:

In this example, we are trying to calculate the time taken by the program to print a statement.

Python3




# importing time module
import time
 
start = time.time()
print("Time Consumed")
print("% s seconds" % (time.time() - start))


Output:

Time Consumed
0.01517796516418457 seconds

Example 2:

In this example, we are trying to calculate the time taken by the program to call a function and print the statement.

Python3




# importing time module
import time
 
 
def gfg():
    start = time.time()
    print("Time consumed")
    end = time.time()
    print("gfg() function takes", end-start, "seconds")
 
 
# Calling gfg
gfg()


Output:

Time consumed
gfg() function takes 0.015180110931396484 seconds

Profiling in Python

Python provides many excellent modules to measure the statistics of a program. This makes us know where the program is spending too much time and what to do in order to optimize it. It is better to optimize the code in order to increase the efficiency of a program. So, perform some standard tests to ensure optimization and we can improve the program in order to increase efficiency. In this article, we will cover How do we profile a Python script to know where the program is spending too much time and what to do in order to optimize it.

Similar Reads

Method 1: Python time module

Time in Python is easy to implement and it can be used anywhere in a program to measure the execution time. By using timers we can get the exact time and we can improve the program where it takes too long. The time module provides the methods in order to profile a program....

Method 2: Python line_profiler

...

Method 3: Python cProfile

...

Contact Us