我需要幫助在我的代碼中應用多處理。我試着閱讀Python文檔的多處理部分,但我只是不知道如何將它應用於我所擁有的。不過,我相信我想要使用的是Pool。下面是我寫的Python腳本,最終將被調用到另一個主腳本的一個組成部分:如何在我的Python代碼中應用多處理?
## servoRemote.py
from franges import drange
from cmath import sqrt as csqrt
from math import atan, degrees, radians, tan, sqrt, floor
import servo
# Declare variables for servo conditional statements:
UR = False
UL = False
BR = False
BL = False
def servoControl(x,y):
global UR, UL, BR, BL
ytop = round((-csqrt((0.3688**2)*(1-((x-0.5)**2)/(0.2067**2)))+0.5).real,3)
ybottom = round((csqrt((0.3688**2)*(1-((x-0.5)**2)/(0.2067**2)))+0.5).real,3)
if (x in list(drange(0.5,0.708,0.001,3)) and y in list(drange(ytop,0.501,0.001,3))):
UR = True
UL = False
BR = False
BL = False
(factor, angle) = linearSF(x,y)
(servo1, servo2) = angleSF(factor,angle)
servo.move(1,servo1)
servo.move(2,servo2)
def linearSF(r,s):
# Calculates the hypotenuse of the gaze:
distr = abs(r-0.4999)
dists = abs(0.50-s)
theta = atan(dists/distr)
b = sqrt(distr**2+dists**2)
# Involved in solving for max x coordinate:
A = 1+0.31412198*tan(theta)**2
B = (-1-0.31412198*tan(theta)**2)**2 - 4*(1+(tan(theta)**2)/3.183477)*(0.207275+0.0785305*tan(theta)**2)
B = csqrt(B)
C = 2+((2*tan(theta)**2)/3.183477)
# Different x equations:
xRight = ((A+B)/C).real
xLeft = ((A-B)/C).real
if (UR == True and UL == False and BR == False and BL == False):
x = xRight
y = -sqrt((0.3688**2)*(1-((x-0.5)**2)/(0.2067**2)))+0.5
# Solve for max hypotenuse given an angle, a:
a = sqrt(abs(x-0.5)**2+abs(0.5-y)**2)
# Final outputs, factor and angle (in degrees):
factor = (b/float(a))
angle = degrees(theta)
return (factor, angle)
def angleSF(factor, angle):
# Angular factors:
S1U = -0.0025641026*angle + 1.230759
S2R = 0.0025641026*angle + 1
if (UR == True and UL == False and BR == False and BL == False):
servo1 = int(floor((S1U*65-78)*factor + 78))
servo2 = int(floor((S2R*65-78)*factor + 78))
return (servo1,servo2)
上面的代碼只針對情況下UR ==真。還有其他有條件的if語句可以遵循不同的條件。提前
while 1:
x = [some continuously incoming data stream]
y = [some continuously incoming data stream]
servoControl(x,y)
再次感謝:大部分的例子,我發現使用multiprocesses使用有限的循環,但我想將這個在一段時間像這樣!我敢肯定,如果我明白如何爲這一個腳本做到這一點,我可能會弄清楚如何將它應用於其他腳本。
共享狀態(您使用全局變量)不適用於多處理。 – monkut
'foo == False'拼寫爲'not foo','foo == True'拼寫爲'foo'。 –
你的代碼太慢了嗎?多少錢?在你想考慮並行化之前,你應該考慮很多優化和組織。 –