[PyQt] Efficiency under nested loop

Russell Valentine russ at coldstonelabs.org
Thu Apr 24 19:48:19 BST 2008


Sergi Blanch i Torné wrote:
> Hi,
> 
> In the discussion about the QListWidget[1] I saw something that happens to me 
> also with the QImage conversion from 12 bits to 8. Remember that I have a 
> problem showing grayscaled images[2] I need to say that the data needs to be 
> process and it means the solution cannot be simply acquire the pictures in 8 
> bits.
> 
> Right now I write a loop for the list and then convert to the array of 
> unsigned chars need by the QImage. It means touch each element two times. The 


I recommend using numpy. I think you will find it useful for more things 
than just this as well.
http://numpy.scipy.org/


convertfrom is your original method
convertfrom2 is slightly speed up without numpy
convertfrom3 is with numpy

TIME: convertfrom  - 2.18s
TIME: convertfrom2 - 1.98s
TIME: convertfrom3 - 0.06s


I changed the lshifts to rshifts, because I'm on little endian.


import random
import array
import time

def convertfrom(image):
     bar,barfoo = image,[]
     for i in range(len(bar)):
         barfoo.append(bar[i].__rshift__(8))
     return array.array('B',barfoo).tostring()

def convertfrom2(image):
     barfoo = []
     for i in xrange(len(image)):
         barfoo.append(image[i].__rshift__(8))
     return array.array('B',barfoo).tostring()

im=array.array('H');
for i in xrange(1200*1024):
     im.append(int(random.random()*2**16));

startTime = time.time()
im2=convertfrom(im)
print "TIME: convertfrom - "+str(time.time() - startTime)+"s"

startTime = time.time()
im2=convertfrom2(im)
print "TIME: convertfrom2 - "+str(time.time() - startTime)+"s"


import numpy

def convertfrom3(image):
     return image.__rshift__(8).astype(numpy.uint8).tostring()

im=numpy.array(im)
startTime = time.time()
im2=convertfrom3(im)
print "TIME: convertfrom3 - "+str(time.time() - startTime)+"s"


More information about the PyQt mailing list