[PyQt] Why does QApplication.processEvents() increase performance?

Brent Villalobos Brent.Villalobos at pdi.dreamworks.com
Tue Apr 28 23:18:22 BST 2009


I have been conducting some performance tests on PyQt4 and I've run into 
a condition that is very counter-intuitive to me.  I am looping over a 
list of QPushButton widgets (4900 of them) and calling their hide() and 
show() methods.  When just calling those two methods, my application 
loops over all of them in about 60 seconds.  However, if I insert an 
"app.processEvents()" call in that loop, I get much better times around 
30 seconds.  Why is adding that processEvents method in the loop causing 
such a dramatic improvement in performance?  I know this isn't the most 
realistic example, but I'm trying to show some people the importance of 
app.processEvents() to not lock up the GUI when doing large operations.  
I would like to have an explanation for the performance improvment.

I'm including sample code to run.  To execute the test, you have to 
press the button in the upper-left hand corner of the window.  It will 
print the total time for each hide/show loop in the console.  Toggle the 
comment for "app.processEvents()" at line #18 to see the difference in 
performance.  Any thoughts?

### Code Start ###

import sys
import time

global startTime
global app
global dlg

from PyQt4 import Qt as qt
from PyQt4 import QtGui

buttons = []
def refresh():
    for j in range(3):
        startTime = time.time()
        for i, b in enumerate(buttons):
            b.hide()
            #app.processEvents()
            b.show()
        print "Hide/show buttons in %f seconds" % (time.time()-startTime)

app = QtGui.QApplication(sys.argv)
dlg = QtGui.QDialog()

xcount = ycount = 70
for i in xrange(xcount):
    for j in xrange(ycount):
        b=qt.QPushButton('BTN', dlg)
        b.setGeometry(qt.QRect(i*34, j*30,34,30))
        buttons.append(b)

        if i == 0 and j == 0:
            b.connect(b, qt.SIGNAL("clicked()"), refresh)

dlg.show()
app.exec_()

### Code End ###



More information about the PyQt mailing list