Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
490 views
in Technique[技术] by (71.8m points)

python - 如何并行化嵌套的for循环,以使其真正更快?(How to parallelize a nested for loop to actually make it faster?)

I am processing an image and I have its pixels in an array of size 1920x1200 (can differ based on the image).

(我正在处理图像,像素为1920x1200大小的阵列(可能会因图像而异)。)

I am iterating through every pixel and increasing some global variables based on different conditions.

(我正在遍历每个像素,并根据不同的条件增加一些全局变量。)

So I basically now have a nested for loop that I use to iterate through pixels.

(因此,我现在基本上有了一个嵌套的for循环,可用于遍历像素。)

variable1 = 0  #variables declared globally
variable2 = 0

# this method gets a pixel and increases some global variables if the conditions are met
def mapp(pixel):
    global variable1
    global variable2

    if(condition):
        variable1 = variable1 + 1
        return
    if(condition2):
        variable2 = variable2 + 1
        return
# im.size[0] is one dimension of the image and im.size[1] is another dimension.
# pix[w,h] is used to access a pixel at coordinates (w,h)

for w in range(0,im.size[0]):
    for h in range(0,im.size[1]):
        mapp(pix[w,h])


#after finishing the iterations I print those variables

I want to make it concurrent so that X processes would run at the same time with each process only processing 1/X of the image, making the program run faster.

(我想使其并发,以便X进程可以同时运行,而每个进程仅处理图像的1 / X ,从而使程序运行得更快。)

How would I do that?

(我该怎么做?)


Is it a good practice to have global variables and have them be possibly increased with each iteration when trying to make a program concurrent or are there any better approaches?

(拥有全局变量并在尝试使程序并发时每次迭代增加它们是否是一个好习惯,还是有更好的方法?)

If so, what are those approches and how do I do it?

(如果是这样,那是什么方法,我该怎么做?)

Is there anything that could go wrong in this situation?

(在这种情况下有什么地方可能出问题吗?)

(I am quite new to Python and concurrency overall)

((对于Python和整体并发我还是很陌生))

  ask by Army translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
等待大神答复

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...