bevyengine / bevy

A refreshingly simple data-driven game engine built in Rust
https://bevyengine.org
Apache License 2.0
36.24k stars 3.57k forks source link

prepare_window hangs for long frame hitches when experiencing background CPU load #8934

Open recatek opened 1 year ago

recatek commented 1 year ago

Bevy version

10.1

Relevant system information

`AdapterInfo { name: "NVIDIA GeForce GTX 1080 Ti", vendor: 4318, device: 6918, device_type: DiscreteGpu, driver: "NVIDIA", driver_info: "516.94", backend: Vulkan }`
`SystemInfo { os: "Windows 10 Pro", kernel: "19045", cpu: "Intel(R) Core(TM) i7-7700K CPU @ 4.20GHz", core_count: "4", memory: "32.0 GiB" }`

What you did

Ran this code with Chrome or some other task in the background, creating periods of higher background CPU usage.

use bevy::prelude::*;

fn main() {
    App::new()
        .add_plugins(DefaultPlugins.set(WindowPlugin {
            primary_window: Some(Window {
                title: "Hitch".to_string(),
                ..Default::default()
            }),
            ..Default::default()
        }))
        .insert_resource(FrameTimer::new())
        .add_system(frame_system)
        .run();
}

#[derive(Resource)]
struct FrameTimer {
    last: std::time::Instant,
}

impl FrameTimer {
    fn new() -> Self {
        Self {
            last: std::time::Instant::now(),
        }
    }
}

fn frame_system(mut timer: ResMut<FrameTimer>) {
    let now = std::time::Instant::now();
    let duration = now - timer.last;
    if duration.as_millis() > 30 {
        println!("{}", duration.as_millis());
    }
    timer.last = now;
}

What went wrong

At higher CPU loads, bevy will get stuck in long hitches -- tracy shows this hang occurring in window::prepare_window.

image

Additional information

This seems like there's some sort of thread contention issue. There's an element of "well, duh" to this where certainly performance will degrade as CPU usage rises, but this is a pretty drastic hitch rather than a gradual framerate drop. I haven't observed behavior like this in other engines, so I'm wondering if there's some trick here to avoiding this issue and presenting a smoother experience without such a frame time contrast?

PPakalns commented 3 weeks ago

Got similar issue that is mentioned in code comment: https://github.com/bevyengine/bevy/blob/main/crates/bevy_render/src/view/window/mod.rs#L199

get_next_texture hangs on Device::wait.

In my case during very heavy GPU workload (multiple ingame screens rendering full game content) get_next_texture hangs in every frame. I am using custom rendering pipelines, shaders so that could be an issue too. But wanted to provide additional information about observed behaviour.

Image