Have you lost your studies? Six tips to improve the running speed of Python code are really delicious

Time:2022-1-13

If someone asks you “what is the fastest programming language?”, You might say, “definitely not python.”

In fact, python runs faster than we think. The reason why we have a preconceived view that Python runs slowly may be our common misuse and lack of usage skills and knowledge.

Recommended articles

Next, let’s see how to use some simple tricks to improve the running performance of our program,Like this article like, collection, attention.

1. Use built-in functions

Many built-in functions in Python are implemented in C and have been well optimized. Therefore, if you are familiar with these built-in functions, you can improve the performance of Python code. Some commonly used built-in functions include sum (), len (), map (), max (), etc.

Suppose we have a list of words, and we want the first letter of each word to be capitalized. At this point, using the map () function is a good choice.

General version:

new_list = []
word_list = ["i", "am", "a", "python", "programmer"]
for word in word_list:
    new_list.append(word.capitalize())

Improved version:

word_list = ["i", "am", "a", "python", "programmer"]
new_list = list(map(str.capitalize, word_list))

Time comparison:

import time
new_list = []
word_list = ["i", "am", "a", "python", "programmer"]

start = time.time()

for word in word_list:
    new_list.append(word.capitalize())
print(time.time() - start, "seconds")

start = time.time()

new_list = list(map(str.capitalize, word_list))
print(time.time() - start, "seconds")

Operation results:

1.0013580322265625e-05 seconds
4.76837158203125e-06 seconds

It can be seen that the second method runs nearly twice as fast

String connection vs join()

In Python, strings are immutable, so we can’t modify them.
Each time we connect multiple strings, we will create a new string, which will cause some performance problems.

General version:

new_list = []
word_list = ["I", "am", "a", "Python", "programmer"]
for word in word_list:
    new_list += word

Improved version:

word_list = ["I", "am", "a", "Python", "programmer"]
new_list = "".join(word_list)

Time comparison:

import time

new_list = []
word_list = ["I", "am", "a", "Python", "programmer"]

start = time.time()
for word in word_list:
    new_list += word
print(time.time() - start, "seconds")

start = time.time()
new_list = "".join(word_list)
print(time.time() - start, "seconds")

Operation results:

4.0531158447265625e-06 seconds
9.5367431640625e-07 seconds

Using the join () function can make the code run four times faster

How to create lists and dictionaries

In general, use[]and{}To create lists and dictionarieslist()anddict{}More efficient operation This is because of the use oflist()anddict{}To create an object, you need to call an additional function

General version:

list()
dict()

Improved version:

()
{}

Time comparison:
To facilitate time comparison, we usetimeitFunction. Let’s run 1 million times to see the time comparison between the two. The code is as follows:

import timeit

slower_list = timeit.timeit("list()", number=10**6)
slower_dict = timeit.timeit("dict()", number=10**6)

faster_list = timeit.timeit("[]", number=10**6)
faster_dict = timeit.timeit("{}", number=10**6)

print(slower_list, "seconds")
print(slower_dict, "seconds")
print(faster_list, "seconds")
print(faster_dict, "seconds")

Operation results:

0.08825178800000001 seconds
0.083323732 seconds
0.019935448999999994 seconds
0.027835573000000002 seconds

It can be seen that our running speed is nearly four times faster

Use f-strings

We already know that concatenating strings can slow down the program.
Another good solution is to use f-strings.

General version:

me = "Python"
string = "Make " + me + " faster"

Improved version:

me = "Python"
string = f"Make {me} faster"

Time comparison:

import time
me = "Python"

start = time.time()
string = "Make " + me + " faster"
print(time.time() - start, "seconds")

start = time.time()
string = f"Make {me} faster"
print(time.time() - start, "seconds")

Operation results:

2.1457672119140625e-06 seconds
9.5367431640625e-07 seconds

It can be seen that our running speed is nearly twice as fast

Using comprehensions

List comprehensions in Python provides us with shorter syntax and even one line of code to realize various powerful functions. In many scenarios where loops are used, we try to use generative syntax

General version:

new_list = []
existing_list = range(1000000)
for i in existing_list:
    if i % 2 == 1:
        new_list.append(i)

Faster version:

existing_list = range(1000000)
new_list = [i for i in existing_list if i % 2 == 1]

Time comparison:

import time

new_list = []
existing_list = range(1000000)

start = time.time()
for i in existing_list:
    if i % 2 == 1:
        new_list.append(i)
print(time.time() - start, "seconds")

start = time.time()
new_list = [i for i in existing_list if i % 2 == 1]
print(time.time() - start, "seconds")

Operation results:

0.16418218612670898 seconds
0.07834219932556152 seconds

It can be seen that our running speed is nearly twice as fast

Appendix – built in functions in Python

We can view Python’s built – in functions through the official website

Have you lost your studies? Six tips to improve the running speed of Python code are really delicious
If we only focus on some short code snippets in the above example, these techniques don’t seem to improve much. In fact, our project is easy to become complex, and the above skills come in handy!

8. Summary

This article focuses on how to use some simple tricks in Python to improve code efficiency, and gives the corresponding code examples.

Have you failed?


Technical exchange

Welcome to reprint, collect, gain, praise and support!

Have you lost your studies? Six tips to improve the running speed of Python code are really delicious

At present, a technical exchange group has been opened, and the group friends have exceeded2000 people, the best way to add notes is: source + Interest direction, which is convenient to find like-minded friends

  • Method ① send the following pictures to wechat, long press identification, and the background replies: add group;
  • Mode ②. Adding micro signal:dkl88191, note: from
  • Mode 3. WeChat search official account:Python learning and data mining, background reply: add group

Have you lost your studies? Six tips to improve the running speed of Python code are really delicious

Recommended Today

Character imaging of Python special effects

“The ancients’ knowledge is weak, but their Kung Fu can only be achieved when they are young and old.” Character imaging, the original image is processed by Python to generate an image completely composed of pure characters. Indoorsman brother official account, character imaging makes your photos not leak. Flying rabbit’s brother’s public address has more […]