加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 站长学院 > PHP教程 > 正文

Python多进程库之一个函数让你设置CPU数和线程数

发布时间:2020-12-13 21:05:59 所属栏目:PHP教程 来源:网络整理
导读:【Python多进程库】1个函数让你设置CPU数和线程数 Tags: Python 多线程 多进程 博客虽水,然亦博主之苦劳也。 如对代码有兴趣的请移步我的 Github:https://github.com/cyh24/multicpu。 如需转载,请附上本文链接,不甚感激! http://blog.csdn.net/cyh_24

【Python多进程库】1个函数让你设置CPU数和线程数

Tags: Python 多线程 多进程

博客虽水,然亦博主之苦劳也。

如对代码有兴趣的请移步我的 Github:https://github.com/cyh24/multicpu。

如需转载,请附上本文链接,不甚感激!
http://blog.csdn.net/cyh_24/article/details/49314709

multicpu

使用multicpu以后,你需要1个函数,就能够定义你程序运行时所需的CPU数量和每一个cpu占用的线程数量

result = multi_cpu(process_job,jobs,cpu_num,thread_num)

cpu_num: 使用的CPU数量.
thread_num: 每一个cpu占用的线程数量.

重点是,代码只有60行不到,你可以很轻松的浏览源码。

安装指南


multicpu 可以直接使用pip就能够安装了

pip install multicpu

或,你也能够用git clone下载源代码,然后用setup.py安装:

git clone git@github.com:cyh24/multicpu.git sudo python setup.py install

“Talk is cheap,show me your performance.”

由于源代码才60行不到,所以,你自己去看完全不会有卡住的地方,这里简单粗鲁地直接上代码:


如果你的程序是 不是IO密集型


import time def process_job(job): time.sleep(1) return job jobs = [i for i in range(20)]

如果你的程序 IO密集型


import time def process_job(job): count = 100000000 while count>0: count -= 1 return job jobs = [i for i in range(20)]

没有使用任何多线程处理的方法:


import time if __name__ == "__main__": result = [] for job in jobs: result.append(process_job(job))

使用了python的线程池:


import time from concurrent import futures if __name__ == "__main__": result = [] thread_pool = futures.ThreadPoolExecutor(max_workers=10) result = thread_pool.map(process_job,jobs)

使用multicpu


import time from concurrent import futures if __name__ == "__main__": result = multi_cpu(process_job,10,1)

效果:


Function Non-Thread Multi-Thread(10) multicpu(10,1) multicpu(10,2)
IO 146.42 (s) 457.53 (s) 16.34 (s) 42.81 (s)
Non-IO 20.02 (s) 2.01 (s) 2.02 (s) 1.02 (s)

How Does it Work?


Feel free to read the source for a peek behind the scenes

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读