Python timeit module

28/12/2020

Programming is not just about accomplishing a task and getting an output we intended to get. It is also about how fast a program runs and execute so that the desired output is achieved. With most of the programming languages, it is not easy to compare how fast out program has run and it is never easy to time a particular piece of code to understand which part of our code is taking the most time to execute. This is the issue which is solved by the Python timeit module.

Python timeit module

Python timeit module allows us to time the execution time of a piece of code without taking into account the background processes which are run to make a code executable. If you need slightly accurate measurements of how your code is performing timeit is the module to go for.

timeit simple example

We will start by using the timeit module directly from the command prompt. timeit module can be used directly from the CLI where we can input a simple loop statement and time it using the shown command:

$ python –version
$ python -m timeit ‘"&".join(str(n) for n in range(1000))’
$ python -m timeit ‘"&".join([str(n) for n in range(1000)])’
$ python -m timeit ‘"&".join(map(str, range(1000)))’

Here is what we get back with this command:

Time of execution from CLI using timeit

In one of the later sections, we will learn how we can manage the number of loops performed to find the optimal number for the execution of a given expression.

Timing a piece of code

If you have a basic python script which you want to measure time for, timeit module is the way to go:

import timeit

# setup code is executed just once
setup_code = "from math import sqrt"

# main code snippet for performance check
code_to_measure =
def example():
mylist = []
for x in range(100):
mylist.append(sqrt(x))

# timeit statement
print(timeit.timeit(setup = setup_code,
stmt = code_to_measure,
number = 10000))

Let’s see the output for this command:

Timing a loop

In this code, we also saw how we can control the number of repetitios the timeit module will perform to find the best time of execution for the program.

Measure time for multi-line code from CLI

We can also measure time for code which spans through multiple lines in the Python CLI. Let’s look at a sample program to see this:

$ python -m timeit -s
> "linuxhint = {}"
> "for n in range(1000):"
> " linuxhint[str(n)] = n"

Here is what we get back with this command:

Timing multi-line code on CLI

Generally comparing two blocks of code

If you don’t want to get into a hassle of using CLI and just want to compare two Python programs so that you know which one runs faster, there is a pretty simple way of achieveing this:

import timeit

start = timeit.default_timer()
funcOne()
print(timeit.default_timer() – start)

start = timeit.default_timer()
funcTwo()
print(timeit.default_timer() – start)

By using the default_timer() function, we start the times again and again to find a difference for the same when it was last started. This can only be used when you have good modular style of writing code so that each pieve of code can be measured separately.

Conclusion

In this lesson, we studied how we can time our code in Python and see their time complexity and efficiency and work over it if the code is too slow.

ONET IDC thành lập vào năm 2012, là công ty chuyên nghiệp tại Việt Nam trong lĩnh vực cung cấp dịch vụ Hosting, VPS, máy chủ vật lý, dịch vụ Firewall Anti DDoS, SSL… Với 10 năm xây dựng và phát triển, ứng dụng nhiều công nghệ hiện đại, ONET IDC đã giúp hàng ngàn khách hàng tin tưởng lựa chọn, mang lại sự ổn định tuyệt đối cho website của khách hàng để thúc đẩy việc kinh doanh đạt được hiệu quả và thành công.
Bài viết liên quan

Top 10 Python Web Frameworks

When you want to make a website, you need HTML, JavaScript and CSS. To create a website using Python, you need a few other...
29/12/2020

Python Requests Module Tutorial

Requests is a popular apache2 licensed module in Python that can be used to interact with HTTP servers such as world wide...
28/12/2020

Regular Expressions using Python 3

Regular Expressions are often seen as this really obscure series of hieroglyphs that one typically copies from the Internet...
29/12/2020
Bài Viết

Bài Viết Mới Cập Nhật

Mua Proxy V6 Nuôi Facebook Spam Hiệu Quả Tại Onetcomvn
03/06/2024

Hướng dẫn cách sử dụng ProxyDroid để duyệt web ẩn danh
03/06/2024

Mua proxy Onet uy tín tại Onet.com.vn
03/06/2024

Thuê mua IPv4 giá rẻ, tốc độ nhanh, uy tín #1
28/05/2024

Thuê địa chỉ IPv4 IPv6 trọn gói ở đâu chất lượng, giá RẺ nhất?
27/05/2024