pthom / imgui_bundle

Dear ImGui Bundle: an extensive set of Ready-to-use widgets and libraries, based on ImGui. Start your first app in 5 lines of code, or less. Whether you prefer Python or C++, this pack has your back!
https://pthom.github.io/imgui_bundle/
MIT License
592 stars 63 forks source link

Release the Python GIL when rendering #171

Closed dcnieho closed 5 months ago

dcnieho commented 5 months ago

In my application i have (at least) two threads, one main thread where all the GUI code runs, and a second thread with an event loop for async code (a lot of the code in the app is async). I notice that when i run this code without a GUI, it is way more performant then when running it with the GUI. My hunch (and i do not know how to verify this) is that this is because rendering and then just waiting for the swap/screen flip to occur blocks and doesn't allow the event loop thread to run as much as it could.

I have tried dirty tricks like keeping track in the BeforeImGuiRender callback how much time has elapsed since the last swap and then sleeping a bit if there is still enough time left until the next swap. This seems to speed up my app, expect it has the nasty side effect of occasionally freezing it for a few seconds, so its not workable.

But this got me thinking. I assume that the GIL is being held all the time. But it should be possible to release it from after the BeforeImGuiRender callback until the start of the next frame, or something along those lines, which would free other python code to run while we await the swap (quite similar to the Model no 2 example here since this is essentially a sleep.

I am not sure if we'd be stepping into untold complexity here with all the various backends, but if it would be possible to release the GIL for those backends where it would make sense, if running from Python in the first place, I think that could do wonders for app performance in some cases. As said, i have not profiled (nor do i know how to approach this), so i have no verified my hunch.

pthom commented 5 months ago

Hello,

Releasing the Gil is a good idea indeed. I spent a few hours on it this morning.

Please do test the pre-built wheels here and tell me if it works: download and unzip the artifacts, then installed the one for your platform.

dcnieho commented 5 months ago

Super! I will test both this and the selection getter for the text editor tonight or tomorrow (wasn't aware of the wheels being built upon commit). Thanks!

dcnieho commented 5 months ago

This runs well for me on windows. With some limited clicking around, it does seem that the parts of my app fed by async data sources is significantly more responsive. So, yay!