讓Python加速運(yùn)行的八種實用技巧分享
1. 使用內(nèi)置函數(shù)和庫
Python的內(nèi)置函數(shù)是用C語言實現(xiàn)的,運(yùn)行速度比純Python代碼快得多。
# 慢速寫法 result = [] for item in iterable: result.append(func(item)) # 快速寫法 - 使用map函數(shù) result = list(map(func, iterable)) # 或者使用列表推導(dǎo)式 result = [func(item) for item in iterable]
2. 利用JIT編譯器 - Numba
Numba是一個JIT(即時)編譯器,可以將Python函數(shù)編譯為機(jī)器碼。
from numba import jit import numpy as np @jit(nopython=True) def sum_array(arr): total = 0.0 for i in range(arr.shape[0]): total += arr[i] return total large_array = np.random.rand(10000000) print(sum_array(large_array))
3. 使用多進(jìn)程處理CPU密集型任務(wù)
Python有GIL(全局解釋器鎖),多線程不適合CPU密集型任務(wù),多進(jìn)程是更好的選擇。
from multiprocessing import Pool def process_data(data): # 數(shù)據(jù)處理邏輯 return result * 2 if __name__ == '__main__': data = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] with Pool(4) as p: # 使用4個進(jìn)程 results = p.map(process_data, data) print(results)
4. 使用Cython將Python編譯為C
Cython允許你編寫C擴(kuò)展模塊,顯著提升性能。
# 保存為example.pyx def compute(int n): cdef int i cdef double res = 0.0 for i in range(n): res += i * i return res
然后創(chuàng)建setup.py:
from distutils.core import setup from Cython.Build import cythonize setup(ext_modules=cythonize('example.pyx'))
編譯并安裝:
python setup.py build_ext --inplace
5. 使用高效的數(shù)據(jù)結(jié)構(gòu)
選擇合適的數(shù)據(jù)結(jié)構(gòu)可以大幅提升性能。
# 頻繁成員檢查使用集合(set)而不是列表 large_list = list(range(1000000)) large_set = set(large_list) # 慢速 if 999999 in large_list: # O(n) pass # 快速 if 999999 in large_set: # O(1) pass
6. 利用NumPy和Pandas進(jìn)行向量化操作
避免Python級別的循環(huán),使用向量化操作。
import numpy as np # 慢速 - Python循環(huán) def slow_dot(a, b): result = 0 for x, y in zip(a, b): result += x * y return result # 快速 - NumPy向量化 def fast_dot(a, b): return np.dot(a, b) a = np.random.rand(1000000) b = np.random.rand(1000000) %timeit slow_dot(a, b) # 約500ms %timeit fast_dot(a, b) # 約2ms
7. 使用lru_cache緩存函數(shù)結(jié)果
對于計算密集型且頻繁使用相同參數(shù)的函數(shù),使用緩存可以避免重復(fù)計算。
from functools import lru_cache @lru_cache(maxsize=128) def expensive_function(x, y): # 模擬復(fù)雜計算 result = 0 for i in range(x): for j in range(y): result += i * j return result # 第一次調(diào)用會執(zhí)行計算 print(expensive_function(100, 100)) # 相同參數(shù)再次調(diào)用會直接返回緩存結(jié)果 print(expensive_function(100, 100))
8. 避免不必要的全局變量訪問
局部變量訪問比全局變量快得多。
# 慢速 - 頻繁訪問全局變量 global_var = 10 def slow_func(): total = 0 for i in range(1000000): total += global_var return total # 快速 - 使用局部變量 def fast_func(): local_var = global_var total = 0 for i in range(1000000): total += local_var return total %timeit slow_func() # 約80ms %timeit fast_func() # 約50ms
總結(jié)
優(yōu)先使用內(nèi)置函數(shù)和庫
對數(shù)值計算使用Numba JIT
CPU密集型任務(wù)使用多進(jìn)程
關(guān)鍵代碼用Cython編譯
選擇高效的數(shù)據(jù)結(jié)構(gòu)
使用NumPy/Pandas向量化操作
緩存函數(shù)結(jié)果避免重復(fù)計算
減少全局變量訪問
根據(jù)你的具體應(yīng)用場景選擇合適的優(yōu)化方法,通常可以帶來幾倍到幾百倍的性能提升!記住在優(yōu)化前先分析性能瓶頸,使用cProfile等工具找出真正需要優(yōu)化的部分。
以上就是讓Python加速運(yùn)行的八種實用技巧的詳細(xì)內(nèi)容,更多關(guān)于Python加速運(yùn)行技巧的資料請關(guān)注腳本之家其它相關(guān)文章!
相關(guān)文章
Pycharm報錯:'NoneType'?object?has?no?attribute?
這篇文章主要給大家介紹了關(guān)于Pycharm報錯:'NoneType'?object?has?no?attribute?'bytes'的解決方法,文中通過圖文將解決的方法介紹的非常詳細(xì),需要的朋友可以參考下2022-02-02使用BeautifulSoup爬蟲程序獲取百度搜索結(jié)果的標(biāo)題和url示例
這篇文章主要介紹了使用BeautifulSoup編寫了一段爬蟲程序獲取百度搜索結(jié)果的標(biāo)題和url的示例,大家參考使用吧2014-01-01