helloSystem / Utilities

Utilities written in PyQt5, meant for use with helloSystem
BSD 2-Clause "Simplified" License
28 stars 29 forks source link

Zeroconf.app draws 100% CPU #29

Closed probonopd closed 3 years ago

probonopd commented 3 years ago

Why?

PreyK commented 3 years ago

You are using a while(true) loop to query the state of the process's launch. This is expensive since it executes the code in the loop in every CPU-cycle (essentially an infinite loop). The problematic loop is on Line 254 (while True:) https://github.com/helloSystem/Utilities/blob/90eba911bac887e72f996a8b9695119c83501c54/Utilities/Zeroconf.app/Zeroconf#L254 Reworking the above code fixes the high CPU-usage. image

The simplest way to fix this would be to add some (even a few ms is enough) delay to the loop's steps. https://stackoverflow.com/questions/4449943/relatively-simple-python-script-using-100-cpu

Ps. Mainly C# developer here, but absolutely love this project, might submit a PR when I dust off my Python skills :D

PreyK commented 3 years ago

Just submitted a PR for this, no major changes just added a bit of delay. https://github.com/helloSystem/Utilities/pull/43

PreyK commented 3 years ago

Just a heads up: This is more of a quick fix because the app uses this loop to process the UI now the UI update will be deferred by the loop's delay. A proper solution for this would be a separate UI thread. (but setting the delay for a very small number like 0.001 probably will work good enough but a bit hacky) https://github.com/helloSystem/Utilities/blob/90eba911bac887e72f996a8b9695119c83501c54/Utilities/Zeroconf.app/Zeroconf#L255

probonopd commented 3 years ago

Thank you very much @PreyK.

I woud like to avoid having to manually deal with Threads in Python at all cost (last time I tried, it turned out way too complicated - almost as bad as having to deal with memory or with pointers).

So, why is using time.sleep() better than using QtWidgets.QApplication.processEvents()?

PreyK commented 3 years ago

Happy to help 👍 It's basically doing the same thing. I just added the time.sleep() in the loop to add a bit of delay so that the loop doesn't get executed in every cycle hammering the CPU constantly (thus 100% usage) I'd be happy to revisit this when I find a better solution without threading :)

probonopd commented 3 years ago

Closing for now since it is not using 100% CPU anymore but feel free to comment here in case you find a better solution. Thank you very much.