#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中的多线程有时候并不能真的提高效率,可以试试多进程
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
问题解答:
要使用线程池来提高Python中的for循环效率,可以使用concurrent.futures库中的ThreadPoolExecutor类来实现。具体步骤如下:
import concurrent.futures
executor = concurrent.futures.ThreadPoolExecutor(max_workers=5)
其中max_workers参数设置线程池的大小,可以根据需要适当调整。
results = []
for i in range(10):
future = executor.submit(my_function, i)
results.append(future)
其中,my_function是需要运行的函数名,i是函数的参数,submit方法会返回一个Future对象,可以将其添加到results列表中。
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)
注意:使用线程池时要注意线程安全问题,避免出现数据竞争等情况。适当设置线程池大小可以提高速度,但过大可能会消耗过多资源。