aevyrie / bevy_framepace

Framepacing and framelimiting for Bevy
https://crates.io/crates/bevy_framepace
Apache License 2.0
239 stars 23 forks source link

Thread parking #55

Closed MOZGIII closed 2 months ago

MOZGIII commented 6 months ago

I coundn't help but notice this crate uses spinlocks while thread parking exists. Why not use thread parking instead?

aevyrie commented 3 months ago

Spinlocking is required, as far as I'm aware, to achieve the sleep timing accuracy needed. If there is a better way, I'm all ears.

MOZGIII commented 3 months ago

Not sure about the accuracy of other methods besides spinlock. What timings and accuracy are we talking about here?

I have looked up the precision of Instant and it seems like it is implemented to provide very accurate timing data - however there's also OS scheduler that can delay even the spinlock for the durations much longer than the precision of the Instant... So, a statement on the accuracy goals might be a good idea to analyze this further.

aevyrie commented 3 months ago

The issue is with sleep, not Instant. I'm pretty ignorant about thread parking, but my understanding is it uses a sleep, and it may not even wake on time. Sleep accuracy is critical, because if you miss the wakeup by microseconds, you can drop frames.

The spinlock I'm using emits instruction to the CPU that we are in a spinlock, which helps with power use significantly. With framepace, you should see extremely low CPU use - that was one of the motivating features. Using a naive spinlock eats up a lot of resources, but this plugin hasn't done that for quite a while.

https://doc.rust-lang.org/std/hint/fn.spin_loop.html

MOZGIII commented 3 months ago

I mention instant as the lower bound for the required accuracy - spinlock uses instant, and thus it is good enough - lower bound of accepted accuracy.

The spinlock I'm using emits instruction to the CPU that we are in a spinlock, which helps with power use significantly. With framepace, you should see extremely low CPU use - that was one of the motivating features. Using a naive spinlock eats up a lot of resources, but this plugin hasn't done that for quite a while.

doc.rust-lang.org/std/hint/fn.spin_loop.html

Yep, I've seen the instructions. How big of an effect do they have though? Much better than the usual spinlock?

aevyrie commented 2 months ago

The difference is pretty significant - it makes it possible to keep CPU use in the single digits when frame time is very low.