Python多進(jìn)程庫(kù)之一個(gè)函數(shù)讓你設(shè)置CPU數(shù)和線程數(shù)
來(lái)源:程序員人生 發(fā)布時(shí)間:2016-04-29 08:39:04 閱讀次數(shù):5172次
【Python多進(jìn)程庫(kù)】1個(gè)函數(shù)讓你設(shè)置CPU數(shù)和線程數(shù)
Tags: Python 多線程 多進(jìn)程
博客雖水,然亦博主之苦勞也。
如對(duì)代碼有興趣的請(qǐng)移步我的 Github:https://github.com/cyh24/multicpu。
如需轉(zhuǎn)載,請(qǐng)附上本文鏈接,不甚感激!
http://blog.csdn.net/cyh_24/article/details/49314709
multicpu
使用multicpu以后,你需要1個(gè)函數(shù),就能夠定義你程序運(yùn)行時(shí)所需的CPU數(shù)量和每一個(gè)cpu占用的線程數(shù)量:
result = multi_cpu(process_job, jobs, cpu_num, thread_num)
cpu_num: 使用的CPU數(shù)量.
thread_num: 每一個(gè)cpu占用的線程數(shù)量.
重點(diǎn)是,代碼只有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行不到,所以,你自己去看完全不會(huì)有卡住的地方,這里簡(jiǎn)單粗魯?shù)刂苯由洗a:
如果你的程序是 不是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)]
沒(méi)有使用任何多線程處理的方法:
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, jobs, 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
生活不易,碼農(nóng)辛苦
如果您覺(jué)得本網(wǎng)站對(duì)您的學(xué)習(xí)有所幫助,可以手機(jī)掃描二維碼進(jìn)行捐贈(zèng)