在python中的multiprocessing.pool.starmap()之后仅使用20%的CPU

时间:2019-06-14 10:04:40

标签: performance python-multiprocessing cpu-usage python-3.7

该程序的目的是通过目录运行,如果文件是excel电子表格,则应将其打开,提取和处理一些数据,然后移至下一个文件。由于这是一个费力的过程,因此我尝试将任务划分为多个线程。即使在此之后,它仅使用了总CPU容量的20%,并没有特别加快速度。

def extract_data(unique_file_names):
    global rootdir
    global newarray
    global counter
    global t0
    string = rootdir + "\\" + str(unique_file_names[0])
    wb = load_workbook(string, read_only = True,  data_only=True)
    ws = wb["Sheet1"]
    df = pd.DataFrame(ws.values)
    newarray = df.loc[4:43,:13].values

    counter = 0
    print("Starting pool")
    pool = ThreadPool(processes=20)
    pool.map(process, unique_file_names)    
    pool.close() 

def process(filename):
    global newarray
    global unique_file_names
    global counter
    global t0
    counter+=1

    try: 
        file_name = rootdir + "/" + str(filename)
        wb = load_workbook(file_name, read_only = True,  data_only=True)
        ws = wb["Sheet1"]
        df = pd.DataFrame(ws.values)
        newarray = np.hstack((newarray, df.loc[4:43,4:13].values))
    except:
        print("Failure")
        pass

    print("Time   %.2f,  Completed  %.2f %% " %((time.clock()-t0),counter*100/len(unique_file_names)))

因此,处理一个电子表格大约需要大约一秒钟半的时间,但是就像我说的,pool.map()几乎没有区别。有什么建议吗?

预先感谢

0 个答案:

没有答案