在使用 bs4、lxml 決議并使用 ThreadPoolExecutor 執行緒遍歷我的檔案時,我遇到的結果非常緩慢。我已經在整個互聯網上搜索了這個更快的替代方案。在 ThreadPoolExecutor 上決議大約 2000 個快取檔案(每個 1.2mb)大約需要 15 分鐘(max_works=500)。我什至嘗試在 Amazon AWS 上使用 64 個 vCPU 進行決議,但速度保持不變。
我想決議大約 100k 個檔案,這需要數小時的決議時間。為什么在多處理時決議不能有效地加速?一個檔案大約需要 2 秒。由于執行緒是并發的,為什么 (max_works=10) 的 10 個檔案的速度也不等于 2 秒?好吧,也許 3 秒就可以了。但是檔案越多,我分配給執行緒的作業人員就越多,這需要很長時間。運行單個檔案/執行緒時,每個檔案大約需要 25 秒,而不是 2 秒。為什么?
在多處理時,我能做些什么來獲得每個檔案所需的 2-3 秒?
如果不可能,有更快的解決方案嗎?
我的決議方法如下:
with open('cache/' filename, 'rb') as f:
s = BeautifulSoup(f.read(), 'lxml')
s.whatever()
有更快的方法來抓取我的快取檔案嗎?
// 多處理器:
from concurrent.futures import ThreadPoolExecutor, as_completed
future_list = []
with ThreadPoolExecutor(max_workers=500) as executor:
for filename in os.listdir("cache/"):
if filename.endswith(".html"):
fNametoString = str(filename).replace('.html','')
x = fNametoString.split("_")
EAN = x[0]
SKU = x[1]
future = executor.submit(parser,filename,EAN,SKU)
future_list.append(future)
else:
pass
for f in as_completed(future_list):
pass
uj5u.com熱心網友回復:
嘗試:
from bs4 import BeautifulSoup
from multiprocessing import Pool
def worker(filename):
with open(filename, "r") as f_in:
soup = BeautifulSoup(f_in.read(), "html.parser")
# do some processing here
return soup.h1.text.strip()
if __name__ == "__main__":
filenames = ["page1.html", "page2.html", ...] # you can use glob module or populate the filenames list other way
with Pool(4) as pool: # 4 is number of processes
for result in pool.imap_unordered(worker, filenames):
print(result)
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/513760.html
