You need to enable JavaScript to run this app. 如何借助多进程优化该数字搜索Python代码的执行效率
优惠活动
大模型
产品
解决方案
定价
更多

如何借助多进程优化该数字搜索Python代码的执行效率

基于multiprocessing的搜索任务并行优化方案

拆分核心逻辑

原来的单进程搜索属于纯CPU密集型任务,且不同任务单元之间无共享状态依赖,完全可以通过多进程把计算负载拆分到多个CPU核心上,无需复杂的进程间同步。拆分维度有两个可选:

  • 外层遍历的ones值序列:每个不同的前导1个数,对应的全排列遍历计算完全独立
  • 内层的perms列表分片:单个全排列对应的目标数计算、分解校验逻辑完全独立
    本次实现选择按外层ones值序列分片,分片粒度适中,避免过细的任务拆分带来的进程调度开销。

具体实现代码

首先导入多进程依赖,保留原有dfac函数逻辑完全不变:

import multiprocessing as mp
from perms import perms

def dfac(n):
    potential_factors = [9, 8, 7, 6, 4, 3, 2, 1]
    factors = [9, 8]
    n //= 72
    while n != 1:
        for f in potential_factors:
            if n % f == 0 and f != 1:
                factors.append(f)
                n //= f
                break
            elif f != 1:
                potential_factors = potential_factors[1:]
                break
            else:
                return ['f']
    return factors[::-1]

然后定义子进程的工作逻辑,把校验结果、进度信息通过队列传回主进程:

def worker_task(ones_sublist, shared_perms, search_index, version_num, result_queue, progress_queue):
    perms_length = len(shared_perms)
    for ones in ones_sublist:
        i = 1
        for p in shared_perms:
            target_num = int('1' * ones + p)
            # 提前加判断:目标数如果不能被72整除,直接判定分解失败,跳过后续循环
            if target_num % 72 != 0:
                result_queue.put({
                    'found': True,
                    'ones': ones,
                    'perm': p
                })
                return
            res = dfac(target_num)
            if len(res) == 1:
                progress_queue.put((ones, i, perms_length))
            else:
                result_queue.put({
                    'found': True,
                    'ones': ones,
                    'perm': p
                })
                return
            i += 1
        progress_queue.put((ones, 'all_perms_done'))
    result_queue.put({'found': False})

最后是主进程的调度逻辑,负责拆分任务、启动子进程、接收结果、统一打印输出:

if __name__ == '__main__':
    version = 1
    perms_length = len(perms)
    index = 17701
    start = 20077
    # 生成所有待遍历的ones值列表
    all_ones = list(range(start, index + 9144 * version, 9))
    # 根据CPU核心数确定进程数量,避免过多进程导致内存开销
    process_num = mp.cpu_count()
    # 平均拆分ones值列表,保证每个进程的负载尽量均匀
    chunk_size = (len(all_ones) + process_num - 1) // process_num
    ones_chunks = [all_ones[i:i+chunk_size] for i in range(0, len(all_ones), chunk_size)]

    result_queue = mp.Queue()
    progress_queue = mp.Queue()

    # 启动所有工作进程
    processes = []
    for chunk in ones_chunks:
        p = mp.Process(
            target=worker_task,
            args=(chunk, perms, index, version, result_queue, progress_queue),
            daemon=True
        )
        p.start()
        processes.append(p)

    # 主进程循环监控结果
    found_result = None
    finished_process = 0
    while finished_process < len(processes):
        # 优先处理结果队列
        if not result_queue.empty():
            res = result_queue.get()
            if res['found']:
                found_result = res
                break
            else:
                finished_process += 1
        # 统一处理进度打印,避免多进程输出乱序
        while not progress_queue.empty():
            prog = progress_queue.get()
            if len(prog) == 3:
                ones_val, i, total = prog
                print(f'{ones_val} ({i} / {total})')
            else:
                ones_val, _ = prog
                print(f'Ones值 {ones_val} 全排列遍历完成')

    # 终止所有仍在运行的子进程,避免孤儿进程占用资源
    for p in processes:
        if p.is_alive():
            p.terminate()

    # 输出最终匹配到的失败项
    if found_result:
        output = f"\n\n\nOnes: {found_result['ones']}\nPerm: {found_result['perm']}\n\n\n"
        print(output)

关键注意事项

  • 不要在子进程中直接调用exit()终止逻辑,所有终止操作由主进程统一控制,避免出现跨进程的异常终止
  • 所有打印输出统一由主进程从队列读取后执行,避免多进程并发写终端导致输出顺序混乱
  • 给目标数增加%72的提前判断,可以跳过大量无需进入dfac循环的无效计算,进一步提升单进程的执行效率
  • 进程数不要超过CPU物理核心数过多,否则会因为进程频繁上下文切换抵消并行收益

内容的提问来源于stack exchange,提问作者Joey

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.25 19:54:02