python 的多线程执行速度

python 的多线程有点鸡肋,适用场景有局限,单位时间多个核只能跑一个线程。

有泳池一个,四个泵,但只有一个人,一人只能开启管理着其中一个,所以四个泵没什么用。但是,如果泵的工作时间与冷却恢复时间是1:3(感谢inoahx指出,已改),那么配置的利用率高达100%。
直接运行代码
single.py
#!/usr/bin/python3
#-*- coding: utf-8 -*-
# author:zhouchao
# 功能:直接运行程序 计算时间

import threading
import sys
import math
import time

lists = [];
for x in range(1,10000000):
    lists.append(x);


length = len(lists);
for x in range(600):
    step = math.ceil(float(length)/600)
    minIndex = step * x
    if minIndex + step > length :
        maxIndex = length
    else:
        maxIndex = minIndex+step

    print(lists[minIndex:maxIndex])
    datetime = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()) 
    fileObject = open("time1.txt",'a+');
    fileObject.write(str(datetime)+"
");
    fileObject.close();

所需时间:134 s

开600 个线程运行同一代码

multiThread.py

#!/usr/bin/python3
#-*- coding: utf-8 -*-
# author:zhouchao
# 功能:600线程计算执行时间


import threading
import sys
import math
import time

lists = [];
for x in range(1,10000000):
    lists.append(x);


def function(i):
    global lists
    length = len(lists);
    step = math.ceil(float(length)/600)
    minIndex = step * i
    if minIndex + step > length :
        maxIndex = length
    else:
        maxIndex = minIndex+step

    print(lists[minIndex:maxIndex])
    datetime = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()) 
    # datetime = str(lists[minIndex:maxIndex])
    fileObject = open("time2.txt",'a+');
    fileObject.write(str(datetime)+"
");
    fileObject.close();


threads = []
for i in range(600):
    t = threading.Thread(target=function , args=(i,))
    threads.append(t)
    t.start()
    t.join()

所需时间:160 s 

原文地址:https://www.cnblogs.com/zc123/p/8469003.html