Skip to main content

autd3_rs/
tuning.rs

1#[cfg(windows)]
2mod imp {
3    use windows_sys::Win32::Media::{timeBeginPeriod, timeEndPeriod};
4    use windows_sys::Win32::System::Threading::{
5        GetCurrentProcess, HIGH_PRIORITY_CLASS, SetPriorityClass,
6    };
7
8    const TIMER_PERIOD_MS: u32 = 1;
9    const TIMERR_NOERROR: u32 = 0;
10
11    pub struct PerfTuning {
12        timer_set: bool,
13        priority_set: bool,
14    }
15
16    impl PerfTuning {
17        #[must_use]
18        pub fn apply() -> Self {
19            // SAFETY: timeBeginPeriod is a thread-safe winmm call; it is paired
20            // with timeEndPeriod(TIMER_PERIOD_MS) in Drop.
21            let timer_set = unsafe { timeBeginPeriod(TIMER_PERIOD_MS) } == TIMERR_NOERROR;
22            // SAFETY: GetCurrentProcess returns a pseudo-handle that needs no
23            // close; SetPriorityClass only reads it.
24            let priority_set =
25                unsafe { SetPriorityClass(GetCurrentProcess(), HIGH_PRIORITY_CLASS) != 0 };
26            Self {
27                timer_set,
28                priority_set,
29            }
30        }
31
32        #[must_use]
33        pub fn timer_boosted(&self) -> bool {
34            self.timer_set
35        }
36
37        #[must_use]
38        pub fn high_priority(&self) -> bool {
39            self.priority_set
40        }
41    }
42
43    impl Drop for PerfTuning {
44        fn drop(&mut self) {
45            if self.timer_set {
46                // SAFETY: matches the earlier timeBeginPeriod(TIMER_PERIOD_MS).
47                unsafe {
48                    timeEndPeriod(TIMER_PERIOD_MS);
49                }
50            }
51        }
52    }
53}
54
55#[cfg(not(windows))]
56mod imp {
57    pub struct PerfTuning;
58
59    impl PerfTuning {
60        #[must_use]
61        pub fn apply() -> Self {
62            Self
63        }
64
65        #[must_use]
66        pub fn timer_boosted(&self) -> bool {
67            false
68        }
69
70        #[must_use]
71        pub fn high_priority(&self) -> bool {
72            false
73        }
74    }
75}
76
77pub use imp::PerfTuning;