为什么程序执行时间和以前一样?
Why is the program execution time the same as before?
出于某种原因,执行时间仍然与没有线程相同。
但如果我添加类似 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()
欢迎来到 the Global Interpreter Lock a.k.a. GIL 的世界。您的函数看起来像 CPU 绑定代码(一些计算、循环、ifs、内存访问等)。抱歉,您不能使用线程来提高 CPU 绑定任务的性能。这是Python的限制。
Python中有释放GIL的函数,例如磁盘 i/o、网络 i/o 以及您实际尝试过的方法:睡眠。事实上,线程确实提高了 i/o 绑定任务的性能。但是算术 and/or 内存访问不会在 Python.
中并行 运行
标准的解决方法是使用进程而不是线程。但由于 not-that-easy 进程间通信,这通常很痛苦。您可能还想考虑使用一些低级库,例如在某些情况下实际释放 GIL 的 numpy(您只能在 C 级别执行此操作,GIL 无法从 Python 本身访问) 或 使用其他一些没有这个限制的语言,例如C#、Java、C、C++ 等等。
出于某种原因,执行时间仍然与没有线程相同。
但如果我添加类似 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()
欢迎来到 the Global Interpreter Lock a.k.a. GIL 的世界。您的函数看起来像 CPU 绑定代码(一些计算、循环、ifs、内存访问等)。抱歉,您不能使用线程来提高 CPU 绑定任务的性能。这是Python的限制。
Python中有释放GIL的函数,例如磁盘 i/o、网络 i/o 以及您实际尝试过的方法:睡眠。事实上,线程确实提高了 i/o 绑定任务的性能。但是算术 and/or 内存访问不会在 Python.
中并行 运行标准的解决方法是使用进程而不是线程。但由于 not-that-easy 进程间通信,这通常很痛苦。您可能还想考虑使用一些低级库,例如在某些情况下实际释放 GIL 的 numpy(您只能在 C 级别执行此操作,GIL 无法从 Python 本身访问) 或 使用其他一些没有这个限制的语言,例如C#、Java、C、C++ 等等。