How to Measure Execution Time in Python?

Measure Execution Time in Python
How to Measure Execution Time in Python?

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Ut elit tellus, luctus nec ullamcorper mattis, pulvinar dapibus leo.

Table of Contents

Methods for Measuring Execution Time on Python

Measure Execution Time in Python

There are many Python modules like time, timeit, and Python datetime that can store the time that the particular section of the program is running. By manipulating or getting the difference between the start and end times a particular section is running, we can calculate the time it took to run the section. 

The following methods can be used to calculate the time difference:

  • The time module in Python provides various functions related to time. This module is included in the standard Python utility modules. The Time module’s time.time() method is used to get the time in seconds since the epoch. Handling of leap seconds is platform-dependent.
  • Python’s datetime library defines a function that can be used primarily to get the current datetime. now() function Returns the current local date and time, which is defined in the datetime module.
  • timeit runs your code snippet millions of times (default is 1000000) so you get the most statistically relevant measure of code execution time.

Measuring Execution Time with time

The time library is quite complete, but the only thing that interests us to measure the execution time is the time().

This method returns the number of seconds, to the nearest microsecond, that has passed since January 1, 1970.

import time

print(time.time()) # 1609954317.943479

To measure the execution time of our programs, it is enough to know the time that has passed before and after executing our program, and the difference will be the time that our code has taken.

import time

start = time.time()

# code to measure

time.sleep(1)

# ————-

end = time.time()

print(end-start) # 1.0005340576171875

In this case, we can see how the elapsed time is practically 1 since time.sleep(1) takes 1 second to execute.

We can also see the time it takes to calculate the first 10000000 even numbers.

import time

start = time.time()

# code to measure

list = [i for i in range(10000000) if i%2==0]

# ————-

end = time.time()

print(end-start) # 1.5099220275878906

On the other hand, we can also create a decorator that uses time, which will allow us to measure the execution time of our functions without repeating so much code. We create the decorator as follows:

def measure_time(function):

     def measure_function(*args, **kwargs):

         start = time.time()

         c = function(*args, **kwargs)

         print(time.time() – start)

         return c

     return measure_function

Now we can use the decorator measure_function with @ before our function, and each time we call it, the time it took to execute will be printed on the screen.

@measure_time

def calculate_pairs(n):

     return [i for i in range(n) if i%2 == 0]

calculate_pairs(10000000)

#1.4356

Measuring Execution Time with timeit

Python also offers us another library called timeit, and it is designed to measure the execution times of small pieces of code. It can be used on the command line or as a function within Python.

The following code snippet allows us to measure the execution time of the statement x=5. The argument number is the number of times the code snippet is executed.

import timeit

time = timeit.timeit(‘x = 5’, number=100000000)

print(time) # 2.173444958

It is important to note that the time returned to us is the sum of all executions. That is, the following example takes 2.17 seconds to execute x=5 a total of 100000000 times.

In the following example, we see how the following list comprehension takes an average of 0.18 seconds to execute.

Know More  How to Measure Distance on Google Maps?

import time it

time = timeit.timeit(‘list = [i for i in range(1000000) if i%2==0]’, number=5)

# calculate the meantime

print(time/5) # 0.18671

Tips and Conclusions

  • To measure the execution time of your programs, take the average of several executions. Due to different factors, you will never get the same result, so it is important to get the average. Look at the different values ​​you get, and if they are very different, consider changing things.
  • If you measure code snippets that take very little time to execute, you will need to average more values.
  • Note that depending on your operating system, the accuracy you’ll get from different libraries may vary.
  • Don’t waste time optimizing codes that are hardly used. Take time to analyze the code that requires optimization and focus your efforts there.

In this article you have learned about how to measure execution time in python😎

5/5 - (1 vote)

Rate This Article:

Leave a Reply

Your email address will not be published. Required fields are marked *