Python 編程:多線程為 for 循環(huán)提速
for 循環(huán)是編程的一個(gè)基本方面,它允許我們迭代序列并高效地執(zhí)行操作。然而,在處理耗時(shí)任務(wù)時(shí),for 循環(huán)的順序性質(zhì)可能成為瓶頸。一個(gè)解決方案是使用線程。學(xué)習(xí):如何使用、何時(shí)使用以及何時(shí)不使用線程。像往常一樣,你可以在我的 GIT 倉(cāng)庫(kù)中找到代碼示例。鏈接在頁(yè)腳。
讓我們從一個(gè)例子開(kāi)始。我們將偽造并模擬一個(gè)耗時(shí)的任務(wù)。我們將使用一個(gè) Python 腳本,該腳本通過(guò) for 循環(huán)對(duì)數(shù)字列表進(jìn)行處理,通過(guò) square_number 函數(shù)將每個(gè)數(shù)字平方:
import time
# List of numbers to process
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
# Function to square a number
def square_number(number):
time.sleep(1) # Simulate a time-consuming task
return number * number
# Using a for loop to process each number
squared_numbers = []
start_time = time.time()
for number in numbers:
squared_numbers.append(square_number(number))
end_time = time.time()
print("Squared numbers:", squared_numbers)
print("Time taken:", end_time - start_time, "seconds")
# Time taken: 10.082990884780884 seconds
這個(gè)腳本按順序處理列表中的每個(gè)數(shù)字,由于 square_number 函數(shù)中的 time.sleep(1) 調(diào)用,每個(gè)數(shù)字耗時(shí) 1 秒。總執(zhí)行時(shí)間為 10.1 秒。
使用多線程優(yōu)化
接下來(lái),我們將使用多線程方法來(lái)優(yōu)化這一點(diǎn),以改善處理時(shí)間。為了使用多線程優(yōu)化上述示例,我們可以使用 Python 的 concurrent.futures 模塊,它為異步執(zhí)行可調(diào)用對(duì)象提供了一個(gè)高級(jí)接口。以下是如何修改腳本以使用多線程:
import time
from concurrent.futures import ThreadPoolExecutor
# List of numbers to process
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
# Function to square a number
def square_number(number):
time.sleep(1) # Simulate a time-consuming task
return number * number
# Using ThreadPoolExecutor for multithreading
squared_numbers = []
start_time = time.time()
with ThreadPoolExecutor(max_workers=10) as executor:
results = executor.map(square_number, numbers)
# Collect the results
squared_numbers = list(results)
end_time = time.time()
print("Squared numbers:", squared_numbers)
print("Time taken:", end_time - start_time, "seconds")
# Time taken: 2.0257720947265625 seconds
在這個(gè)優(yōu)化的腳本中,我們使用 ThreadPoolExecutor 創(chuàng)建一個(gè)線程池。executor.map 函數(shù)將 square_number 函數(shù)分布到線程中,以并行方式處理數(shù)字。通過(guò)將 max_workers 設(shè)置為 5,我們?cè)试S最多 5 個(gè)線程同時(shí)運(yùn)行,這應(yīng)該會(huì)顯著減少總處理時(shí)間。請(qǐng)隨意調(diào)整 max_workers 參數(shù),以找到特定用例的最佳線程數(shù)。
何時(shí)使用多線程
正如你所見(jiàn),多線程可以在各種場(chǎng)景中提供顯著的速度提升。但它并不適用于所有任務(wù)。以下是多線程特別有益的一些典型用例:
I/O 綁定任務(wù):
- 文件 I/O:讀取和寫(xiě)入文件,特別是處理大文件或多個(gè)文件時(shí)。
- 網(wǎng)絡(luò) I/O:同時(shí)處理多個(gè)網(wǎng)絡(luò)連接,例如網(wǎng)絡(luò)抓取、下載文件或處理 web 服務(wù)器中的請(qǐng)求。
- 數(shù)據(jù)庫(kù)操作:執(zhí)行 I/O 綁定的數(shù)據(jù)庫(kù)查詢(xún),例如獲取或更新大型數(shù)據(jù)集。
并發(fā)任務(wù):
- 實(shí)時(shí)數(shù)據(jù)處理:實(shí)時(shí)處理來(lái)自多個(gè)傳感器或流的數(shù)據(jù),例如在 IoT 應(yīng)用中。
- GUI 應(yīng)用程序:通過(guò)在后臺(tái)運(yùn)行耗時(shí)任務(wù),保持用戶(hù)界面的響應(yīng)性。
獨(dú)立任務(wù)的并行處理:
- 批量處理:處理大量可以并行執(zhí)行的獨(dú)立任務(wù),例如圖像處理或數(shù)據(jù)轉(zhuǎn)換任務(wù)。
- 模擬:同時(shí)運(yùn)行多個(gè)模擬或蒙特卡洛實(shí)驗(yàn)。
何時(shí)不使用多線程
雖然多線程可以提供顯著的速度提升,但它并不總是每個(gè)問(wèn)題的最好解決方案。以下是它可能不適用的一些場(chǎng)景:
- CPU 綁定任務(wù):如果任務(wù)嚴(yán)重依賴(lài) CPU 并且不涉及太多等待(如純數(shù)學(xué)計(jì)算),使用 multiprocessing 模塊創(chuàng)建單獨(dú)的進(jìn)程可能更有效。
- 全局解釋器鎖 (GIL):在 CPython 中,全局解釋器鎖可能會(huì)限制多線程在 CPU 綁定任務(wù)中的性能提升。在這種情況下,多進(jìn)程或使用沒(méi)有 GIL 的實(shí)現(xiàn),如 Jython 或 IronPython,可能更有效。
- 復(fù)雜的共享狀態(tài):跨多個(gè)線程管理復(fù)雜的共享狀態(tài)可能會(huì)引入與競(jìng)態(tài)條件、死鎖和線程安全性相關(guān)的挑戰(zhàn)和錯(cuò)誤。
通過(guò)了解任務(wù)的性質(zhì)和潛在瓶頸,你可以決定多線程是否是應(yīng)用程序的適當(dāng)解決方案。
專(zhuān)業(yè)提示 — 使用裝飾器
裝飾器可以用來(lái)以更優(yōu)雅和可重用的方式為函數(shù)添加多線程。裝飾器是一個(gè)函數(shù),它接受另一個(gè)函數(shù)并擴(kuò)展其行為,而不需要顯式修改它。
import time
from concurrent.futures import ThreadPoolExecutor, as_completed
# Decorator to add multithreading
def multithreaded(max_workers=5):
def decorator(func):
def wrapper(*args, **kwargs):
with ThreadPoolExecutor(max_workers=max_workers) as executor:
future_to_args = {executor.submit(func, arg): arg for arg in args[0]}
results = []
for future in as_completed(future_to_args):
arg = future_to_args[future]
try:
result = future.result()
except Exception as exc:
print(f'{arg} generated an exception: {exc}')
else:
results.append(result)
return results
return wrapper
return decorator
# Function to square a number
@multithreaded(max_workers=5)
def square_number(number):
time.sleep(1) # Simulate a time-consuming task
return number * number
# List of numbers to process
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
# Using the decorated function
start_time = time.time()
squared_numbers = square_number(numbers)
end_time = time.time()
print("Squared numbers:", squared_numbers)
print("Time taken:", end_time - start_time, "seconds")
使用裝飾器處理多線程不僅簡(jiǎn)化了代碼,還使其更可重用和更清晰。你可以輕松地將 @multithreaded 裝飾器應(yīng)用于任何需要并行執(zhí)行的函數(shù),為優(yōu)化你的 Python 代碼提供了一種靈活而強(qiáng)大的方式。
結(jié)論
多線程是優(yōu)化 Python 中 for 循環(huán)的強(qiáng)大工具,特別是對(duì)于 I/O 綁定和并發(fā)任務(wù)。通過(guò)利用 concurrent.futures 模塊,你可以顯著減少處理時(shí)間并提高程序的效率。然而,評(píng)估你的特定用例以確定多線程是否是最佳方法至關(guān)重要,特別是當(dāng)你處理 CPU 綁定任務(wù)或復(fù)雜的共享狀態(tài)時(shí)。通過(guò)仔細(xì)考慮和實(shí)施,多線程可以大大增強(qiáng)你的應(yīng)用程序的性能。