Python 多重处理仅在首次运行后才快速

标签 python python-3.x python-multiprocessing

我有一个脚本,它使用多重处理来打开约 200k .csv 文件并对其执行计算。工作流程如下:

1) 考虑一个包含约 200k .csv 文件的文件夹。每个 .csv 文件包含以下内容:

.csv 文件示例:

0, 1
2, 3
4, 5
...
~500 rows

2) 该脚本将所有 .csv 文件的列表保存在 list()

3) 由于我有 8 个可用处理器,该脚本将包含约 200k .csv 文件的列表分为 8 个列表。

4) 脚本调用do_something_with_csv() 8次并并行计算。

在线性模式下,执行时间约为 4 分钟。

并行和串行,如果我第一次执行脚本,需要更长的时间。如果我执行第二次、第三次等等,大约需要 1 分钟。看起来 python 正在缓存某种 IO 操作?看起来是因为我有一个进度条,例如,如果我执行到进度条为5k/200k并终止程序,则下次执行将非常快地执行前5k,然后减慢速度。

Python版本:3.6.1

伪Python代码:

def multiproc_dispatch():
        lst_of_all_csv_files = get_list_of_files('/path_to_csv_files')
        divided_lst_of_all_csv_files = split_list_chunks(lst_of_all_csv_files, 8)

        manager = Manager()
        shared_dict = manager.dict()

        jobs = []
        for lst_of_all_csv_files in divided_lst_of_all_csv_files:
            p = Process(target=do_something_with_csv, args=(shared_dict, lst_of_all_csv_files))
            jobs.append(p)
            p.start()

        # Wait for the worker to finish
        for job in jobs:
            job.join()

def read_csv_file(csv_file):
    lst_a = []
    lst_b = []
    with open(csv_file, 'r') as f_read:
        csv_reader = csv.reader(f_read, delimiter = ',')
        for row in csv_reader:
            lst_a.append(float(row[0]))
            lst_b.append(float(row[1]))
    return lst_a, lst_b


def do_something_with_csv(shared_dict, lst_of_all_csv_files):
    temp_dict = lambda: defaultdict(self.mydict)()
    for csv_file in lst_of_all_csv_files:
        lst_a, lst_b = read_csv_file(csv_file)
        temp_dict[csv_file] = (lst_a, lst_b)

    shared_dict.update(temp_dict)


if __name__ == '__main__':
    multiproc_dispatch()

最佳答案

毫无疑问,RAM 缓存正在发挥作用,这意味着第二次加载文件的速度会更快,因为数据已经在 RAM 中,而不是来自磁盘。 (努力在这里找到好的引用资料,欢迎任何帮助) 这与多处理无关,甚至与 python 本身也无关。

自问题编辑以来不相关我认为并行运行时代码花费较长持续时间的原因来自于从每个子进程内访问的 shared_dict 变量(参见例如 here )。在 python 中的进程之间创建和发送数据很慢,应该减少到最低限度(这里你可以为每个作业返回一个字典,然后合并它们)。

关于Python 多重处理仅在首次运行后才快速,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60190164/

相关文章:

Python 多处理 : object passed by value?

python - ThreadPoolExecutor、ProcessPoolExecutor 和全局变量

python - Flask - 带有动态标签的切换按钮

python - 尝试访问 multiprocessing.Pool 工作进程中的持久数据时出现不稳定的运行时异常

python - Python 3 中的多处理、多线程和异步

python - 如何选择 pandas 中一组的最后一行?

python - 为什么 python 不能矢量化 map() 或列表理解

python - python的多行微调器?

python - 如何为字典键值制作自定义排序功能?

python - 根据数据框中的 id 比较两个数据框列