You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Python中高效组织大型函数并优化执行速度

优化多函数顺序执行的效率与代码结构

你的代码逻辑已经完全符合「找到第一个返回结果的函数就终止后续执行」的需求,但可以通过重构让代码更简洁易维护,同时结合一些策略进一步提速:

代码结构优化

把所有待调用的函数按优先级存入列表,通过循环迭代调用,避免重复的if-return模板代码:

def find_document(reference_number, date, document):
    print('Please Wait !')
    # 按「命中率从高到低/执行速度从快到慢」排序函数
    check_functions = [
        one_date_c,
        c_messy_year,
        c_du_au_format,
        n_du_au_format,
        combined_dates_start_with_N,
        combined_dates_start_with_C
    ]
    
    for func in check_functions:
        result = func(reference_number, date, document)
        if result:
            return result

这个写法和原代码逻辑完全一致——只要某个函数返回真值,就立即返回并终止后续函数的执行,同时新增或调整函数顺序时,只需要修改check_functions列表即可。

额外提速策略

  1. 调整函数优先级:统计实际场景中各个函数的命中率和执行耗时,把命中率最高、执行最快的函数放在列表最前面,这样能更早命中有效结果,减少不必要的函数调用。
  2. 优化单个函数性能:针对每个大型函数内部做优化,比如:
    • 移除冗余计算步骤
    • 替换为更高效的数据结构或算法
    • 如果存在重复参数调用的情况,用functools.lru_cache缓存函数结果(注意参数需为可哈希类型,若document是不可哈希对象,可考虑提取关键哈希字段)
  3. 进阶并行试探(IO密集型场景适用):如果这些函数是IO密集型(比如涉及文件读取、网络请求),可以用线程池同时启动多个函数,一旦某一个返回有效结果就终止其他任务。示例代码如下:
from concurrent.futures import ThreadPoolExecutor, as_completed

def find_document(reference_number, date, document):
    print('Please Wait !')
    check_functions = [
        one_date_c,
        c_messy_year,
        c_du_au_format,
        n_du_au_format,
        combined_dates_start_with_N,
        combined_dates_start_with_C
    ]
    
    with ThreadPoolExecutor(max_workers=len(check_functions)) as executor:
        # 提交所有任务
        futures = {executor.submit(func, reference_number, date, document): func for func in check_functions}
        for future in as_completed(futures):
            result = future.result()
            if result:
                # 取消剩余未完成的任务
                for f in futures:
                    if not f.done():
                        f.cancel()
                return result

注意:CPU密集型场景不建议用并行,反而会因为线程切换增加开销,优先用前面的顺序执行+优先级调整方案。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.16 09:47:28