如何正确地将以下循环并行化?(Python)

如何正确地将以下循环并行化?(Python),python,parallel-processing,python-multiprocessing,Python,Parallel Processing,Python Multiprocessing,先讲一点背景知识。我有大约10.000个pdf文件。我想将这些文件的每一页转换成JPEG文件,然后使用Google Vision API对其进行OCR。我知道将PDF文件转换为JPEG是愚蠢的,因为我可以用API直接对PDF文件进行OCR。然而,这意味着将文件上传到谷歌云存储的一个存储桶中,这需要花费时间和金钱。目前,除了使用PDF文件的存储解决方案外,没有其他方法在PDF文件上使用Vision API 由于这是一项计算成本很高的任务,我尝试使用多处理模块将其并行化。到目前为止,我已经在这个模块

先讲一点背景知识。我有大约10.000个pdf文件。我想将这些文件的每一页转换成JPEG文件,然后使用Google Vision API对其进行OCR。我知道将PDF文件转换为JPEG是愚蠢的,因为我可以用API直接对PDF文件进行OCR。然而,这意味着将文件上传到谷歌云存储的一个存储桶中,这需要花费时间和金钱。目前,除了使用PDF文件的存储解决方案外,没有其他方法在PDF文件上使用Vision API

由于这是一项计算成本很高的任务,我尝试使用多处理模块将其并行化。到目前为止,我已经在这个模块上试用了apply和map选项。这些都没有产生令人满意的结果。“传统”方式仍优于两者

我对并行化还不熟悉,但我想知道这是否可能,并且为每个PDF文件分配一个处理器以使其运行得更快是有意义的

请在下面找到我使用的代码:

from multiprocessing import Pool
import multiprocessing as mp
import numpy as np
from time import time
import os # Directory library
import PyPDF2
import fnmatch
import glob
import numpy as np
import pandas as pd
import pytesseract
import sys
from pdf2image import convert_from_path 
from PyPDF2 import PdfFileReader
import os
import multiprocessing
import sys
sys.path.append(r"K:\xxx")
import defs_mp


# Setting directory
path = r"D:\xxx"
os.chdir(path)

# 1) Listing all files in directory and keeping PDFs      
listOfFiles = defs_mp.getListOfFiles(path)
    
# Keeping the pdf files
pdf_files = list()

for file in listOfFiles:
    if file.endswith(".pdf"):
        pdf_files.append(file)
     
start = time()
# 4) Reading the PDF file
for i in range(1,len(pdf_files)):        
    # Counter to store images of each page of PDF to image 
    image_counter = 1
    # Number of pages in pdf
    page_num = PdfFileReader(pdf_files[i]).getNumPages()

    # Read the files in batches of 10 pages to bypass any lack of RAM memory issues
    for x in range(1,page_num,10):
        pages = convert_from_path(pdf_files[i], dpi=400, first_page=x, last_page = min(x+10-1,page_num))       

        # Iterate through all the pages stored above 
        for page in pages:            
            # Save the image of the page in system 
            page.save(pdf_files[i].replace(".pdf","") + "_" + str(image_counter)+".jpg", 'JPEG') 
                
            # Increment the counter to update filename 
            image_counter = image_counter + 1                             
    del pages

end = time()
single_time = end-start

start = time()


# Step 1: Init multiprocessing.Pool()
pool = mp.Pool(mp.cpu_count())

# Step 2: `pool.apply` the `howmany_within_range()`
if __name__ == '__main__':
    with Pool(10) as p:
        p.map(defs_mp.pdf_to_jpg, pdf_files)

# Step 3: Don't forget to close
pool.close()    

end = time()
apply_time = end-start

print( single_time - apply_time)
PS:我在一台windows机器上(R53600-16gb内存)