python如何利用线程池或其他方法提高代码for循环运行效率

#python如何利用线程池或其他方法提高以下代码for循环运行效率?##我的电脑是16线程#

特别注意的是:是在anaconda的jupter notebook下编写和执行代码


#最终运行版本#1#
#TRIGRSAll-part-1最终版本-从两个excel中读取I、D序列,以“测试I-D”组合命名被复制的文件夹,修改txt文本第a行b列封装函数,批量依次运行exe程序
import pandas as pd# 读取 Excel 文件
import os
dI = pd.read_excel('F:\TRIGRS测试\I.xlsx')
dD = pd.read_excel('F:\TRIGRS测试\D.xlsx')
# 获取某一列的数据并转化为列表-定义变量I和D的取值列表
I_list = dI['降雨强度'].tolist()
D_list = dD['持续时间'].tolist()
print(I_list)
print(D_list)
def modify_txt_file(file_path, a, b, value):
            with open(file_path, "r+") as f:
                lines = f.readlines()
                line = lines[a-1].split()
                line[b-1] = str(value)
                lines[a-1] = " ".join(line) + "\n"
                f.seek(0)
                f.writelines(lines)
                f.truncate() 
# 遍历I和D的取值组合,生成多个文件夹并复制文件
for I in I_list:
    for D in D_list:
        folder_name = f"测试{I}-{D}"
        os.makedirs(os.path.join("F:\\TRIGRS测试\\测试文件", folder_name))
        os.system(f"xcopy /E /I \"F:\\TRIGRS测试\\TRIGRS模型模板10m\" \"F:\\TRIGRS测试\\测试文件\\{folder_name}\"")
         # 修改input.txt文件内容
        input_file = os.path.join("F:\TRIGRS测试\测试文件\\", folder_name, "tr_in.txt")
        modify_txt_file(input_file, 6, 5, D * 3600)
        modify_txt_file(input_file, 24, 2, D * 3600)
        modify_txt_file(input_file, 70, 1, D * 3600)
        line10 = f"{0.001 * I / 86400:.2e}"
        modify_txt_file(input_file, 22, 1, line10)
        
        # 运行index.exe文件
        os.chdir(os.path.join("F:\\TRIGRS测试\\测试文件\\", folder_name))
        topoindex_file = os.path.join("F:\\TRIGRS测试\\测试文件\\", folder_name, "topoindex.exe")
 
 
 

```

python中的多线程有时候并不能真的提高效率,可以试试多进程

  • 你可以参考下这篇文章:python+基于Jupyter notebook完成卷积神经网络和Dlib的笑脸识别+口罩识别
  • 除此之外, 这篇博客: Python3.8环境配置Anaconda3+jupter notebook配置设置中的 第一部分安装Anaconda 部分也许能够解决你的问题, 你可以仔细阅读以下内容或跳转源博客中阅读:
  • 1.Anaconda下载
    官方下载地址:https://www.anaconda.com/products/individual
    目前最新是python3.8,默认为3.8,下载64bit版本(根据自己电脑来,一般现在都是64位)
    在这里插入图片描述
    2.Anaconda安装
    直接双击或者右键管理员运行
    在这里插入图片描述
    在这里插入图片描述
    next,默认就行,all Users(方便电脑有多用户使用)选Just Me有一个问题要注意,如果账户用户名是中文,之后安装路径包含非英文字符会影响程序运行

    在这里插入图片描述
    自己选路径
    在这里插入图片描述
    环境变量PATH一定要勾起
    在这里插入图片描述
    anaconda安装完毕
    在这里插入图片描述
    之前勾选了PATH,这些系统环境变量应该就装上了,没勾选可以自行添加
    在这里插入图片描述
    在powershell中看看conda版本和python
    在这里插入图片描述

  • 以下回答由chatgpt基于相关博客总结生成:

    问题解答:

    要使用线程池来提高Python中的for循环效率,可以使用concurrent.futures库中的ThreadPoolExecutor类来实现。具体步骤如下:

    1. 导入concurrent.futures库
    import concurrent.futures
    
    1. 创建ThreadPoolExecutor对象并设置线程池大小
    executor = concurrent.futures.ThreadPoolExecutor(max_workers=5)
    

    其中max_workers参数设置线程池的大小,可以根据需要适当调整。

    1. 使用submit方法将任务提交给线程池
    results = []
    for i in range(10):
        future = executor.submit(my_function, i)
        results.append(future)
    

    其中,my_function是需要运行的函数名,i是函数的参数,submit方法会返回一个Future对象,可以将其添加到results列表中。

    1. 使用as_completed方法获取已完成的任务的结果
    for future in concurrent.futures.as_completed(results):
        result = future.result()
        print(result)
    

    其中,as_completed方法会返回一个迭代器,包含已完成的任务的Future对象。可以通过result方法获取任务的结果,并进行处理。

    完整示例代码如下:

    import concurrent.futures
    
    def my_function(num):
        # do something
        return result
    
    executor = concurrent.futures.ThreadPoolExecutor(max_workers=5)
    
    results = []
    for i in range(10):
        future = executor.submit(my_function, i)
        results.append(future)
    
    for future in concurrent.futures.as_completed(results):
        result = future.result()
        print(result)
    

    注意:使用线程池时要注意线程安全问题,避免出现数据竞争等情况。适当设置线程池大小可以提高速度,但过大可能会消耗过多资源。