【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占用的线程数量:
cpu_num: 使用的cpu数量.
thread_num: 每一个cpu占用的线程数量.
重点是,代码只有60行不到,你可以很轻松的浏览源码。
安装指南
multicpu 可以直接使用pip就能够安装了
pip install multicpu
或,你也能够用git clone下载源代码,然后用setup.py安装:
“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)]
@H_403_146@ 没有使用任何多线程处理的方法:
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