python多线程和多进程对比
Posted 妞溜溜
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了python多线程和多进程对比相关的知识,希望对你有一定的参考价值。
1、纯计算 多线程只用了一个cpu 45%左右 多进程用两个cpu 90%左右
# coding=utf-8 from multiprocessing import Pool # 多线程版本from multiprocessing.dummy import Pool import sys, os import time def timetask(times): while 1: pass if __name__ == ‘__main__‘: startTime = time.time() worknum = 2 # time : 55.9383509159 processnum = 2 # 进程版本 processnum:2, time : 55.9383509159;processnum:1,time : 108.528738976 ;线程版本 processnum:2,time : 55.0623002052 pool = Pool(processnum) for i in range(worknum): pool.apply_async(timetask, (i, )) pool.close() pool.join() endTime = time.time() print "time :", endTime - startTime
2、涉及io 多线程、多进程都用两个cpu 90%左右
# coding=utf-8 from multiprocessing import Pool import sys, os import time def timetask(times): cmd="tar zcfPh /nerri_%s.tar.gz /tmp" % times os.system(cmd) if __name__ == ‘__main__‘: startTime = time.time() worknum = 2 # time : 55.9383509159 processnum = 2 # 进程版本 processnum:2, time : 55.9383509159;processnum:1,time : 108.528738976 ;线程版本 processnum:2,time : 55.0623002052 pool = Pool(processnum) for i in range(worknum): pool.apply_async(timetask, (i, )) pool.close() pool.join() endTime = time.time() print "time :", endTime - startTime
以上是关于python多线程和多进程对比的主要内容,如果未能解决你的问题,请参考以下文章
Python高阶(一) - 单线程、多线程和多进程的效率对比测试