Python教程

python并行编程

本文主要是介绍python并行编程,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

参考网站:https://python-parallel-programmning-cookbook.readthedocs.io/zh_CN/latest/index.html

多进程模板

def show_predict_batch(predict_model_list, predict_path):
    """
    批量处理预测模型
    @predict_model_list: 预测的模型列表
    @predict_path: 预测模型存放路径
    return: None
    """
    for i, predict_model in enumerate(tqdm(predict_model_list)):
        try:
            save_predict(predict_model, predict_path)
        except KeyError:
            print("predict_model: ", predict_model)
        except Exception as e:
            raise e


def parallel_show_predict(model_list, predict_path, n_workers=8):
    """
    多进程处理
    """
    if len(model_list) < n_workers:
        n_workers = len(model_list)
    chunk_len = len(model_list) // n_workers

    chunk_lists = [model_list[i:i+chunk_len] for i in range(0, (n_workers-1)*chunk_len, chunk_len)]
    chunk_lists.append(model_list[(n_workers - 1)*chunk_len:])
    
    process_list = [Process(target=show_predict_batch, args=(chunk_list, predict_path, )) for chunk_list in chunk_lists]
    for process in process_list:
        process.start()
    for process in process_list:
        process.join()
这篇关于python并行编程的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!