Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

如何设置线程池的大小 #38

Open
diaosichengxuyuan opened this issue Aug 26, 2020 · 0 comments
Open

如何设置线程池的大小 #38

diaosichengxuyuan opened this issue Aug 26, 2020 · 0 comments

Comments

@diaosichengxuyuan
Copy link
Owner

1.CPU密集型 VS IO密集型

我们可以把任务分为计算密集型和IO密集型。
计算密集型任务的特点是要进行大量的计算,消耗CPU资源,比如实验室进行模型训练等,全靠CPU的运算能力。这种计算密集型任务虽然也可以用多线程完成,但是线程越多,花在线程切换的时间就越多,CPU执行任务的效率就越低,所以,要最高效地利用CPU,计算密集型任务同时进行的数量应当等于CPU的核心数。计算密集型任务由于主要消耗CPU资源,因此,代码运行效率至关重要。Python这样的脚本语言运行效率很低,完全不适合计算密集型任务。对于计算密集型任务,最好用C语言编写。
IO密集型任务一般涉及到网络、磁盘IO等操作,这类任务的特点是CPU消耗很少,任务的大部分时间都在等待IO操作完成(因为IO的速度远远低于CPU和内存的速度)。对于IO密集型任务,任务越多,CPU效率越高,但也有一个限度。常见的大部分任务都是IO密集型任务,比如Web应用,一个web请求中的耗时主要在前后端网络IO通信,后端集群间的IO通信,数据库IO通信等,而CPU真正运算的耗时却很少。

2.如何设置线程池大小

在《linux多线程服务器端编程》中有一个思路,CPU计算和IO的阻抗匹配原则。如果线程池中的线程在执行任务时,CPU密集计算所占的时间比重为P(0<P<=1),而系统一共有C个CPU,为了让CPU跑满而又不过载,线程池的大小经验公式 T=C/P,在此,T只是一个参考,考虑到P的估计并不是很准确,T的最佳估值可以上下浮动50%。

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant