美文网首页
python 多线程运算和普通运算的时间对比

python 多线程运算和普通运算的时间对比

作者: Do_More | 来源:发表于2017-07-15 15:55 被阅读0次
import threading
from queue import Queue
import copy
import time

def job(l, q):
    res = sum(l)
    q.put(res)

def multithreading(l):
    q = Queue()
    threads = []
    for i in range(4):
        t = threading.Thread(target=job,args=(copy.copy(l),q), name='T%i' % i)
        t.start()
        threads.append(t)
    [t.join() for t in threads]
    total = 0
    for _ in range(4):
        total += q.get()
    print(total)

def normal(l):
    total = sum(l)
    print(total)

if __name__ == '__main__':
    l = list(range(1000000))
    s_t = time.time()
    normal(l * 4)
    print('normal: ',time.time() - s_t)
    s_t = time.time()
    multithreading(l)
    print('multithreading: ', time.time() - s_t)

result:

1999998000000
normal:  0.09929490089416504
1999998000000
multithreading:  0.09315609931945801

相关文章

网友评论

      本文标题:python 多线程运算和普通运算的时间对比

      本文链接:https://www.haomeiwen.com/subject/tgxzhxtx.html