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
- Addicted, I recently gave the company a large visual screen (with source code)
- So elegant, four Python automatic data analysis artifacts are really fragrant
- After combing for more than half a month, we have carefully prepared 17 knowledge and thinking maps. This time, we should clarify statistics
- Year end summary: 20 visual large screen templates, directly apply Zhenxiang (the source code is attached at the end of the article)
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 usetimeit
Function. 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
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!
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