为了测试多线程效率,我写了一段货物工人模型代码,假如一个卡车上有20件货,每件货有重量,1kg花费1s,2kg花费2s,以此类推,以此模型建立代码如下:
# coding:utf-8
import threading
import time
from random import randint
# 货物源
goods = []
for n in range(20):
goods.append(randint(1, 5))
# 工人货物模型
class MyThread(threading.Thread):
def __init__(self, thread_id, name):
threading.Thread.__init__(self)
self.thread_id = thread_id
self.name = name
def run(self):
print self.name + '开始工作'
do_work(self.name)
print self.name + '完成工作'
# 处理货物
def do_work(thread_name):
while len(goods) > 0:
if len(goods) > 0:
# 从搬运货物的那一刻起货物就已经不存在货源了
wight = goods[0]
goods.remove(wight)
time.sleep(wight)
print thread_name + '花费了 ' + str(wight) + ' 秒'
# 工人
workers = ['张三']
threads = []
thread_id = 0
first_time = time.time()
for worker in workers:
thread_id += 1
thread = MyThread(thread_id, worker)
thread.start()
threads.append(thread)
# 等待所有线程完成
for t in threads:
t.join()
last_time = time.time()
print "总耗时: " + str(last_time - first_time) + " 秒"
单工人工作效率:
张三开始工作
张三花费了 5 秒
张三花费了 3 秒
张三花费了 5 秒
张三花费了 4 秒
张三花费了 5 秒
张三花费了 1 秒
张三花费了 5 秒
张三花费了 4 秒
张三花费了 3 秒
张三花费了 3 秒
张三花费了 5 秒
张三花费了 3 秒
张三花费了 5 秒
张三花费了 5 秒
张三花费了 4 秒
张三花费了 4 秒
张三花费了 4 秒
张三花费了 1 秒
张三花费了 3 秒
张三花费了 2 秒
张三完成工作
总耗时: 74.0130000114 秒
改变工人数量增加到4个:
张三开始工作
李四开始工作
王五开始工作
赵六开始工作
张三花费了 1 秒 王五花费了 1 秒
李四花费了 2 秒
赵六花费了 2 秒
王五花费了 3 秒
李四花费了 3 秒
张三花费了 5 秒
赵六花费了 5 秒 李四花费了 2 秒
王五花费了 3 秒
赵六花费了 1 秒
张三花费了 3 秒
李四花费了 3 秒
赵六花费了 2 秒
张三花费了 2 秒
李四花费了 1 秒
王五花费了 5 秒
王五完成工作
赵六花费了 4 秒
赵六完成工作
张三花费了 5 秒
张三完成工作
李四花费了 5 秒
李四完成工作
总耗时: 16.004999876 秒
测试完成,效率杠杠的,当然可以考虑用这个模型来延申,比如工人成本,效率成本,这一批货物该找多少工人更划算。