小练手:用Python实现多线程计算大数组元素和

刚学Python三四天,记得不久前面试被问过一道用多线程实现计算大数组元素之和的问题,就顺路用Python来实现了一下。

刚学Python不久,如果程序上有什么实现错误,请各位大哥不吝指点下哈~~

代码如下:

#coding: UTF-8

"""
经过非正规的测试,多线程并行计算并未像想象中那样会比串行计算快。
相反,在我的PC上运行后,多线程并行计算反而慢了。
不知是计算量不够大,还是怎么。(本身内存有限,无法无限加大,在有限测试范围内,结果如上)
过程是:随着计算线程数的增加,计算时间会下降,但到了一定数量(不同机器有所不同)后,计算时间反而增加。
因为很大一部分增加的时间是耗费在线程的创建上的。
"""


import threading
import random
import time

class calthread(threading.Thread):
    #初始化函数
    def __init__(self,threadname,cond,startN,endN):
        threading.Thread.__init__(self,name = threadname)
        self.cond = cond
        self.startN = startN
        self.endN = endN
        #print "MyName: " + threadname +",start--" +str(startN) +",end--"+str(endN)
    #业务函数
    def run(self):
        global sumN,alist,countFinish
        temp = 0
        for i in range(self.startN,self.endN + 1):
            temp = temp + alist[i]
        #累加计算和,并累加完成计数器
        self.cond.acquire()
        countFinish += 1
        sumN += temp
        #print "MyName: " + self.getName() +",mySum--" +str(temp) +",countFinish--"+str(countFinish)+",currentTotalSum---"+str(sumN)+"\n"
        global threadN
        if(countFinish == threadN):
            print "End time of threadCal -- " + str(time.time())
            print "The total sum : " + str(sumN) + "\n"
        self.cond.release()

#获取线程锁
cond = threading.Condition()
#目标计算数组的长度
alen = 10000000
#执行计算工作的线程长度
threadN = 10000
#随机初始化数组元素
alist = []
#alist = [random.uniform(1,1000) for x in range(0,alen)]
for i in range(1,alen+1):
    alist.append(i)

#执行线程对象列表
threadL  = [] 
t = alen/threadN
print "初始化线程"
for x in range(0,threadN):
    startN = x*t
    endN = 0
    if((x+1)*t >= alen):
        endN = alen - 1
    else:
        if(x == threadN - 1):
            endN = alen - 1
        else:
            endN = (x+1)*t - 1
    #向列表中存入新线程对象
    threadTT = calthread("Thread--"+str(x),cond,startN,endN)
    threadL.append(threadTT)

#总计完成线程计数器
countFinish = 0
sumN = 0
print "Start time of threadCal--"+ str(time.time())
for a in threadL:
    a.start()

time.sleep(10)
normalSum = 0
print "Start time of normalCal--"+ str(time.time())
for n in range(0,alen):
    normalSum += alist[n]
print "End time of normalCal--"+ str(time.time())

print "Normal : " + str(normalSum) + "\n"

结语:

   经过非正规的测试,多线程并行计算并未像想象中那样会比串行计算快。
相反,在我的PC上运行后,多线程并行计算反而慢了。
不知是计算量不够大,还是怎么。(本身内存有限,无法无限加大,在有限测试范围内,结果如上)
过程是:随着计算线程数的增加,计算时间会下降,但到了一定数量(不同机器有所不同)后,计算时间反而增加。
因为很大一部分增加的时间是耗费在线程的创建上的。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值