Accelerating for loops with list methods in Python -


i have loops in python iterates 2.5 million times , it's taking time result. in js can make happen in 1 second python in 6 seconds on computer. must use python in case. here code:

            in xrange(k,p,2):                 arx = process[i]                 ary = process[i+1]                 j in xrange(7,-1,-1):                     nx = arx + dirf[j]                     ny = ary + dirg[j]                     ind = ny*w+nx                     if data[ind] == e[j]:                                process[c]=nx                         c=c+1                         process[c]=ny                         c=c+1                         matrix[ind]=1 

here lists code: process = [none] * (11000*4) it's items replaced integers after it's assignment.

dirf = [-1,0,1,-1,1,-1,0,1] dirg = [1,1,1,0,0,-1,-1,-1] e = [9, 8, 7, 6, 4, 3, 2, 1]  

the data list consists of 'r' informations pixels of rgba image. data = imgobj.getdata(0)

how can boost this. doing wrong? there other approaches loops? thanks.

here few suggestions improving code:

that inner xrange being used lot: if made regular list , did this:

inner = range(7,-1,-1) # make actual list for(a,b,c): #first     #stuff     in inner # reference actual list , not generator 

evidence :

n = range(7,-1,-1) def one():     z = 0     k in xrange(100):         in n:             z+=1  def two():     z = 0     k in xrange(100):         in xrange(7,-1,-1):             z+=1  if __name__ == '__main__':     import timeit     print("one:")     print(timeit.timeit("one()",number=1000000 ,setup="from __main__ import one"))     print("two:")     print(timeit.timeit("two()",number=1000000 ,setup="from __main__ import two"))  "result"  one: 37.798637867 two: 63.5098838806 

if code wrote comparable, appear indicate referencing inner list , not generating speeds up. [edit] referencing local variable faster accessing global. if correct place list definition close loop possible without having generate every time.

you changing process twice. if it's not needed, choose one.

as mentioned in comments, you're working images. not sure if following relevant, perhaps use opencv, has python api c code. might speed up. others have mentioned: numpy , own cython extensions speed considerably.


Comments

Popular posts from this blog

python - pip install -U PySide error -

arrays - C++ error: a brace-enclosed initializer is not allowed here before ‘{’ token -

cytoscape.js - How to add nodes to Dagre layout with Cytoscape -