python - 为什么程序执行时间和以前一样?
问题描述
由于某种原因,执行时间仍然与没有线程的情况相同。
但是,如果我添加类似的东西,time.sleep(secs)
那么目标 def 内的工作显然是线程化的d
。
def d(CurrentPos, polygon, angale, id):
Returnvalue = 0
lock = True
steg = 0.0005
distance = 0
x = 0
y = 0
while lock == True:
x = math.sin(math.radians(angale)) * distance + CurrentPos[0]
y = math.cos(math.radians(angale)) * distance + CurrentPos[1]
Localpoint = Point(x, y)
inout = polygon.contains(Localpoint)
distance = distance + steg
if inout == False:
lock = False
l = LineString([[CurrentPos[0], CurrentPos[1]],[x,y]])
Returnvalue = list(l.intersection(polygon).coords)[0]
Returnvalue = calculateDistance(CurrentPos[0], CurrentPos[1],
Returnvalue[0], Returnvalue[1])
with Arraylock:
ReturnArray.append(Returnvalue)
ReturnArray.append(id)
def Main(CurrentPos, Map):
threads = []
for i in range(8):
t = threading.Thread(target = d, name ='thread{}'.format(i), args =
(CurrentPos, Map, angales[i], i))
threads.append(t)
t.start()
for i in threads:
i.join()
解决方案
欢迎来到Global Interpreter Lock aka GIL的世界。您的函数看起来像是受 CPU 限制的代码(一些计算、循环、ifs、内存访问等)。抱歉,您不能使用线程来提高 CPU 绑定任务的性能。这是 Python 的限制。
Python 中有一些释放 GIL 的函数,例如磁盘 i/o、网络 i/o 以及您实际尝试过的一个:sleep。事实上,线程确实提高了 i/o 绑定任务的性能。但是算术和/或内存访问不会在 Python 中并行运行。
标准的解决方法是使用进程而不是线程。但这通常是痛苦的,因为进程间通信并不那么容易。您可能还想考虑使用一些低级库,例如在某些情况下实际发布 GIL 的 numpy(您只能在 C 级别执行此操作,GIL 无法从 Python 本身访问)或使用其他没有此限制的语言,例如 C#, Java、C、C++ 等。
推荐阅读
- blockchain - 如何打开 Parity 浏览器界面?
- javascript - 精灵动画闪烁
- drupal - 如何从 Drupal Commerce 中的国家代码获取国家名称
- plot - xaxis 类别未正确绘制多个系列 highcharts 使用 php-mysql 动态填充的值
- node.js - 如果键不在猫鼬模式中,则返回信息
- python - 处理列表和一个元素不是列表类型
- flutter - Flutter 在卡片内创建图像和文本
- angular - 如何向 Angular 过渡添加参数?
- ionic-framework - Ionic 3 表单未将值发送到后端
- android-studio - 当我尝试在 ubuntu 14.04 中安装 android studio