本文主要对比测试Python的多线程和多进程模块在CPU类型和I/O的任务操作时的效率

一 测试CPU消耗类型任务

在一台多核CPU的服务器上执行多线程代码,理论上代码执行时会利用多余的CPU核心来提升性能。但是由于Python的GIL的存在,使用多线程来执行CPU繁重的任务,未必能得到性能提升。但是GIL又必不可少,因为在Python解释器中执行线程是不安全的,也就是说为了保证Python线程执行时的安全,Python提供了一个全局锁,同一时刻,只允许一个线程获得这个全解锁并执行。

CPU消耗类型任务

def f(n):    list=[]    for x in range(n):        x=x*x        list.append(x)

1.单个线程测试

#!/usr/sbin/pythonimport threadingdef f(n):    list=[]    for x in range(n):        x=x*x        list.append(x)if __name__ == '__main__':   threads=2   tasks=[]   for i in range(1,threads):      thread=threading.Thread(target=f(10000000))      tasks.append(thread)   for j in tasks:      j.start()   for j in tasks:      j.join()
real	0m4.965suser	0m4.104ssys	0m0.797s

使用单线程执行时间大约为4.9秒

2.使用2个线程

设置 threads=3

real	0m8.469suser	0m7.480ssys	0m0.981s

使用两个线程执行以上任务,性能反而下降了很多

3.使用4个线程

设置 threads=5

real	0m16.016suser	0m14.712ssys	0m1.285s

4.使用8个线程

设置 threads=9

real	0m31.374suser	0m29.231ssys	0m2.108s

通过以上测试可以得知,使用Python的多线程模块,线程数越多,执行CPU消耗类型的任务时,效率越低。

5.单个进程测试

参考文档: