Search code examples
pyqtpyqt5profilingtiming

How can I profile events in a PyQt application?


This stack overflow answer seems to provide a really clean way to monitor the duration of all Qt events in C++. I'm interested in doing something similar in Python for a PyQt5 application.

The high level goal is to have profiling we can optionally enable to get hard numbers for what is making the application feel slow. How long did the paint take? How long did that mouse click take? Any ideas?


Solution

  • You could just pythonify the C++ code in the linked answer:

    from PyQt5.QtCore import QElapsedTimer
    from PyQt5.QtWidgets import QApplication, QPushButton
    
    class MyApplication(QApplication):
    
        t = QElapsedTimer()
    
        def notify(self, receiver, event):
            self.t.start()
            ret = QApplication.notify(self, receiver, event)
            if(self.t.elapsed() > 10):
                print(f"processing event type {event.type()} for object {receiver.objectName()} " 
                      f"took {self.t.elapsed()}ms")
            return ret
    
    
    if __name__ == "__main__":
        app = MyApplication([])
        ....
        app.exec()