Python 多线程工作速度较慢
你好 我试图学习python中的多线程功能,并编写了以下代码:Python 多线程工作速度较慢,python,multithreading,Python,Multithreading,你好 我试图学习python中的多线程功能,并编写了以下代码: import time, argparse, threading, sys, subprocess, os def item_fun(items, indices, lock): for index in indices: items[index] = items[index]*items[index]*items[index] def map(items, cores): count =
import time, argparse, threading, sys, subprocess, os
def item_fun(items, indices, lock):
for index in indices:
items[index] = items[index]*items[index]*items[index]
def map(items, cores):
count = len(items)
cpi = count/cores
threads = []
lock = threading.Lock()
for core in range(cores):
thread = threading.Thread(target=item_fun, args=(items, range(core*cpi, core*cpi + cpi), lock))
threads.append(thread)
thread.start()
item_fun(items, range((core+1)*cpi, count), lock)
for thread in threads:
thread.join()
parser = argparse.ArgumentParser(description='cube', usage='%(prog)s [options] -n')
parser.add_argument('-n', action='store', help='number', dest='n', default='1000000', metavar = '')
parser.add_argument('-mp', action='store_true', help='multi thread', dest='mp', default='True')
args = parser.parse_args()
items = range(NUMBER_OF_ITEMS)
# print 'items before:'
# print items
mp = args.mp
if mp is True:
NUMBER_OF_PROCESSORS = int(os.getenv("NUMBER_OF_PROCESSORS"))
NUMBER_OF_ITEMS = int(args.n)
start = time.time()
map(items, NUMBER_OF_PROCESSORS)
end = time.time()
else:
NUMBER_OF_ITEMS = int(args.n)
start = time.time()
item_fun(items, range(NUMBER_OF_ITEMS), None)
end = time.time()
#print 'items after:'
#print items
print 'time elapsed: ', (end - start)
当我使用mp参数时,它的工作速度较慢,在我有4个CPU的机器上,计算结果大约需要0.5秒,而如果我使用单个线程,则大约需要0.3秒
我做错什么了吗
我知道有Pool.map()和e.t.c,但它产生子进程而不是线程,据我所知,它工作得更快,但我想编写自己的线程池。Python没有真正的多线程,因为有一个称为“”的实现细节。实际上一次只运行一个线程,Python在线程之间切换。(Python的第三方实现,如can。) 至于为什么您的程序在多线程版本中速度较慢,这取决于,但是在为Python编写代码时,需要注意GIL,因此我们不相信通过向程序添加线程可以更有效地处理CPU负载
其他需要注意的事项包括,例如,用于解决CPU绑定负载的和,以及用于解决I/O绑定负载的(最小)和(巨大的厨房水槽)。只有当您有IO绑定的线程时,您才会看到Python线程吞吐量的增加。如果您所做的是CPU受限的,那么您将不会看到任何吞吐量增加 在Python中启用线程支持(通过启动另一个线程)似乎也会降低一些速度,因此您可能会发现总体性能仍然受到影响
当然,其他Python实现有不同的行为 这个答案有点模棱两可,如果没有GIL,线程还可以提高CPU工作负载的性能。事实上,这正是来自其他线程环境的人们对线程的期望。当然,还有其他方法可以增强Python中CPU负载的处理+但总的来说,答案是1。