How To Speed Up The Python Code?

  Solace  Infotech    April 21, 2021    283

 

We all know that Python is one of the most popular programming all over the world. These days, it is being used in competitive programming because of its simple syntax and rich libraries. You can almost do anything with Python from data science, machine learning, signal processing to  data visualization. But many people claim that python is a bit slow while solving grave problems. Time to execute a program depends on the code that you write. Knowing some tips to optimize the code will help you to speed up the python code. Let’s see the top 10 tips to speed up python code.

Top 10 Tips To Speed Up Python Code –

1. Use Proper Data Structure-

Use of proper data structures has significant effect on runtime. Python includes tuple, list, set and directory as built-in data structures. Most of the people use the list in all cases, but it is not a good choice. Basically use of proper data structures depends on your task. You can use tuple instead of list, because iterating over tuple is easier than iterating over a list.

2. Use Built In Functions And Libraries-

Python includes lots of library functions and modules written by expert developers and have been tested thoroughly. Hence, these functions are efficient and able to speed up the code-no need to write the code if the function is already available in the library. Let us see a simple example-

#code1
newlist = []
for word in oldlist:
    newlist.append(word.upper())

 

#code2
newlist = map(str.upper, oldlist)

 

The second code is faster than the first code because library function map() has been used. These functions are easy to use for beginners too. 

3. Do Not Use Global Variables-

Python has global keyword to declare global variables. Global variable takes higher time during operation than local variable. Using few of them save form unnecessary memory usage. Also, Python scoops up a local variable more rapidly than a global one. While navigating external variables, Python is genuinely slow. A few other programming languages oppose the unplanned use of global variables. The counter is because of side effects like higher runtime. Hence, try to use a local variable rather than a global one whatever possible. Also, you can make a local copy before use it in a loop, saving time.

4. Try To Minimize The Use Of For Loop-

It is hard to  avoid the use of for loop. But whenever you can avoid it, do so. For loop is dynamic in Python and its runtime is more than a while loop. Nested for loop is more time consuming, two nested loops will take the square of the time in a single for loop.

code1
for i in big_it:
    m = re.search(r'\d{2}-\d{2}-\d{4}', i)
    if m:
        …
date_regex = re.compile(r'\d{2}-\d{2}-\d{4}')

for i in big_it:
    m = date_regex.search(i)
    if m:
        ...

In such cases, it will be better to use a suitable replacement. Also, if for loops are inevitable, move the calculation outside the loop. It will save more time. We can see it in example as given. Here the second code is faster than first code since the calculation has been done outside the loop. 

5.Use List Comprehension-

List comprehension offers a shorter syntax. It is handful when another list is made based on an existing list. Loop is important in any code. Sometimes the syntax in a loop becomes large. In such cases, you can use list comprehension.

 

L = []
for i in range (1, 1000):
    if i%3 == 0:
        L.append (i)

Using list comprehension, it would be:

L = [i for i in range (1, 1000) if i%3 == 0]

Here, the second code requires less time than the first code. Approach to list comprehension is short and more precise. Mostly there is not more difference in small codes. But in an extensive development, it can save time. 

6. Do Not Use Dot Operation-

Try to avoid dot operation. To know it in detail, let us see the below program-

import math
val = math.sqrt(60)

Rather than writing a code like this, write code like below-

from math import sqrt
val = sqrt(60)

This is because when you call a function with . (dot), it first calls   __getattribute()__ or __getattr()__ which then uses dictionary operation that takes time. Hence try to use from module import function.

7. Make Use Of Generators-

In python, generator is a function that returns an iterator when keyword yield is called. Generators optimize memory. At a time they return single item rather than all at a time. If your list includes lots of data and you need to use one data at a time, use generators. Generators compute data in pieces, so function can return a result when called upon and retain its state. Generators stores the function state by stopping code after the caller generates the value, and it continues to run from where it is stopped. As the generators access and compute the on-demand value, a significant part of data does not need to be saved completely in memory. This results in memory savings, and speeding up the code.

8. Concatenate Strings With Join-

Concatenation is common when you work with strings. Mostly, in python, we concatenate with ‘+’. In every step, the “+” operation creates a new string and copies old material. It takes more time and hence is inefficient. To speed up Python code, you have to use join() to concatenate strings strings.

code1
x = "My" + "name" + "is" + "john" 
print(x)
code2
x = " ".join(["My", "name", "is", "john"])
print(x)

Here, the first code prints “Mynameisjohn” and second code prints “My name is john”. The join() operation is more faster and efficient than ‘+’. It also keeps the code clean. So if you want a cleaner and faster code, start using join() rather than ‘+’ to concatenate strings. 

9. Use The Latest Release Of Python-

Python is updated and upgraded regularly, and every release is faster and more optimized. Hence use the latest version of python. 

10. Replace range() with xrange()-

Note that this is applicable for python 2 users.

These functions are used to iterate anything in for loop. In case of range(), it saves all the numbers in the range in memory. But xrange() just saves the range of numbers that should be displayed. Return type of range() is a list, and that of xrange() is an object. As xrange() takes less memory, it takes less time. Hence use xrange() rather than range() whenever possible. 

You can know top 7 Python GUI frameworks at- Top 7 Python GUI Frameworks In 2020

Wrap Up-

The value of python is increasing day by day and these are some of the tips that reduce the runtime of python code. There can be few others too. 


 Article keywords:
python, python development, technology, software

 


 Share this article: 
Print Digg StumbleUpon del.icio.us Facebook Yahoo! Buzz Twitter Google Bookmarks LinkedIn MySpace Orkut PDF Scoopeo Viadeo Add to favorites
      

© Copyright - Articles XP