tauri-apps / tray-icon

Tray icons for Desktop Applications.
Apache License 2.0
183 stars 27 forks source link

chore: Reduce CPU load in examples by polling each 16 ms #144

Closed kuvaus closed 2 months ago

kuvaus commented 2 months ago

This tiny PR adds a small delay of 16 ms (60fps) to event_loop to reduce CPU load.

Currently the Tao and Winit examples use 100% CPU load on 1 thread because Controlflow:Poll fires on every CPU cycle. This can be reduced to be less than 1% by introducing small sleep time on the event loop thread.

I think 16 ms (60fps) delay is acceptable as for example windows default timer has a resolution of 15.6 ms. Of course users can comment the std::thread::sleep line to undo the change.

This affects only the Tao and Winit examples, Egui seems to already handle the update loop so that the CPU load is not high.

There is also a reference to issue https://github.com/tauri-apps/tray-icon/issues/83#issuecomment-1697773065 which explains how users can change the structure of the event loop with MenuEvent::set_event_handler and TrayIconEvent::set_event_handler to be more like Tauri.

    // We add delay of 16 ms (60fps) to event_loop to reduce cpu load.
    // This can be removed to allow ControlFlow::Poll to poll on each cpu cycle
    // Alternatively, you can set ControlFlow::Wait or use MenuEvent::set_event_handler,
    // see https://github.com/tauri-apps/tray-icon/issues/83#issuecomment-1697773065
    std::thread::sleep(core::time::Duration::from_millis(16));