当前位置:编程学习 > python >>

python threading效果测试

刚把golang的routine测试了一下,情不自禁转python2.7的threading进行测试。(python3测试结果比python2.7要差一些)

由于python的性能问题,我们把循环降低了2个数量级。

通过测试数据,可以肯定的是python多线程分配到了每个逻辑CPU。但每个逻辑CPU的利用率都很低,怀疑是python多线程中每个时刻只有1个线程在运行,时不时换换CPU而已,所以效率很低,这也是python多线程被大家称为假象的原因。而且线程调度开销过高,多线程明显比单线程耗时高很多。

#!/usr/bin/env python
#-*- coding:utf-8 -*-

from threading import Thread
import math,time

def dothings(s,starttime):
    i=0
    while True:
        if i==10000000:break
        d=i*i
        d=math.sqrt(d)
        i+=1
    ti = time.time()
    print "thread %d cost %d seconds."%(s,ti-starttime)

def test(ng):
    starttime=time.time()
    ths=[]
    for i in range(ng):
        th = Thread(target=dothings,args=(i,starttime))
        ths.append(th)
    for th in ths:
        th.start()
    for th in ths:
        th.join()

if __name__=="__main__":
    for i in range(4):
        print "thread %d."%(i+1)
        test(i+1)

thread 1.
thread 0 cost 3 seconds.
thread 2.
thread 0 cost 11 seconds.
thread 1 cost 11 seconds.
thread 3.
thread 2 cost 17 seconds.
thread 0 cost 18 seconds.
thread 1 cost 18 seconds.
thread 4.
thread 0 cost 24 seconds.
thread 1 cost 25 seconds.
thread 3 cost 25 seconds.
thread 2 cost 25 seconds.

 
摘自 python.cn

补充:Web开发 , Python ,
CopyRight © 2022 站长资源库 编程知识问答 zzzyk.com All Rights Reserved
部分文章来自网络,