标签云

微信群

扫码加入我们

WeChat QR Code

I have for loops in python that iterates nearly 2.5 million times and it's taking so much time to get a result. In JS I can make this happen in nearly 1 second but Python does it in 6 seconds on my computer. I must use Python in this case. Here is the code:for i in xrange(k,p,2):arx = process[i]ary = process[i+1]for j in xrange(7,-1,-1):nx = arx + dirf[j]ny = ary + dirg[j]ind = ny*w+nxif data[ind] == e[j]: process[c]=nxc=c+1process[c]=nyc=c+1matrix[ind]=1Here is some lists from code:process = [None] * (11000*4) it's items will be replaced with 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 is consists of 'r' informations from pixels of an rgba image.data = imgobj.getdata(0)How can I boost this. What am I doing wrong? Is there any other approaches about for loops? Thanks.


it takes 34.9 milliseconds to iterate 2.5million timeson my machine (it is slow but it is not 6 seconds slow).

2019年04月19日34分43秒

If you have to work with them; you should ask about them: what do they do? What is the purpose? Here's a good getting-started reference: How to optimize for speed

2019年04月19日34分43秒

libraries like numba, numerical python (numpy.org), or cython (cython.org) will give you some options to improve performance

2019年04月19日34分43秒

The way you are timing it may skew things - taking time.time() before and after and subtracting is not best practice; instead, use the timeit module to time the whole script, and use profiling to get detailed information about what is slowing it down. I can't quite follow what your pastebin'd code is doing, but it does look like numpy would be a good option - both for speed and readability.

2019年04月18日34分43秒

Also, consider that questions about performance issues and general best practice in otherwise working code might be better asked on codereview.SE.

2019年04月19日34分43秒

Your set of timings for assignments doesn't show a speedup of a tenth of a second - that e-08 at the end means the difference is actually roughly a nanosecond. Your timings for not calling xrange every time around the loop gives a speedup of (63.5 - 37.8)/100,000 seconds which is just under 26 microseconds. Even in a critical inner loop, these types of microoptimisations are likely to have an utterly negligible effect on the overall running time.

2019年04月19日34分43秒

Yes, I agree, I forgot to read the exponent, will remove that section

2019年04月18日34分43秒

The bit you've left in is nearly as bad, though, since a) you didn't average the timing across the number of passes, and b) the change you're testing against affects the whole outer loop once. Even if OPs outer loop iterates quite a bit more than your example, you've provided evidence that they might save, at the very most, a few milliseconds off their six second run time.

2019年04月18日34分43秒