多线程对一些任务的处理如io任务 网络请求任务有明显的加速
记录下改变线程数 对任务完成时间的影响
纯sleep 短视频批量剪辑
最终效果好的线程数目12 4
实验环境
python
多线程模块 进度显示模块
from progress.bar import IncrementalBar from concurrent.futures import ThreadPoolExecutor, as_completed
测试函数 随机数等待 平均等待0.5s
import random,time def f(i): time.sleep(random.random()) return i
6核笔记本cpu插电 Intel(R) Core(TM) i7-9750H CPU @ 2.60GHz
线程数:完成时间 bug实际线程数要额外加1
{0: 4.453978061676025, 1: 2.8310091495513916, 2: 2.3860023021698, 3: 1.613670825958252, 4: 1.4489991664886475, 5: 1.633991003036499, 6: 1.211998462677002, 7: 1.007110834121704, 8: 0.8080122470855713, 9: 1.0049970149993896, 10: 0.6600701808929443, 11: 1.0269966125488281}
bug修复 函数平均等待1s
{6: 2.7679660320281982, 7: 2.364999771118164, 8: 1.7919583320617676, 9: 1.6459925174713135, 10: 1.8652105331420898, 11: 1.8589973449707031, 12: 1.8350036144256592}
结论 线程约2倍下对此类任务加速效果最好
实际场景测试
python 调用命令行ffmpeg os.system剪辑视频去除片尾3s 同时 提前使用模块获取视频长度
58个视频 视频平均长度:13.455172413793104 平均大小:2.811196672505346
import ffmpeg
{1: 11.968335390090942, 2: 7.046592473983765, 3: 5.27799391746521, 4: 4.8334197998046875, 5: 4.4410669803619385, 6: 4.682313442230225, 7: 4.508931636810303, 8: 4.626992225646973, 9: 4.665976047515869, 10: 4.5992937088012695, 11: 4.543792486190796, 12: 4.627867698669434, 13: 4.518102407455444, 14: 4.62638521194458, …}
加速后时间消耗为33%
结论 4核心基本达到最大加速了之后加速无明显收益同时因为开始扎堆添加任务 导致进度显示不平滑而是最后几秒扎堆显示完成
原文链接:https://www.cnblogs.com/adenosine/p/16243352.html
原创文章,作者:优速盾-小U,如若转载,请注明出处:https://www.cdnb.net/bbs/archives/6807