xtap_core_lib/
hardware.rs1use crate::error::Result;
7use rayon::prelude::*;
8
9pub struct HardwareMaster;
11
12impl HardwareMaster {
13 pub fn logical_cpus() -> usize {
15 num_cpus::get()
16 }
17
18 pub fn physical_cpus() -> usize {
20 num_cpus::get_physical()
21 }
22
23 pub fn init_global_pool(threads: Option<usize>) -> Result<()> {
26 let t = threads.unwrap_or_else(Self::logical_cpus);
27 rayon::ThreadPoolBuilder::new()
28 .num_threads(t)
29 .build_global()?;
30 Ok(())
31 }
32
33 pub fn parallel_process<T, R, F>(items: Vec<T>, f: F) -> Vec<R>
36 where
37 T: Send,
38 R: Send,
39 F: Fn(T) -> R + Sync + Send,
40 {
41 items.into_par_iter().map(f).collect()
42 }
43}
44
45#[cfg(feature = "gpu")]
47pub mod gpu {
48 use wgpu;
49
50 pub async fn check_gpu_status() {
51 let instance = wgpu::Instance::default();
52 let adapters = instance.enumerate_adapters(wgpu::Backends::all());
53 for adapter in adapters {
54 println!("检测到 GPU: {:?}", adapter.get_info().name);
55 }
56 }
57}
58
59#[cfg(test)]
60mod tests {
61 use super::*;
62
63 #[test]
64 fn logical_cpus_positive() {
65 assert!(HardwareMaster::logical_cpus() >= 1, "逻辑核心数应 ≥ 1");
66 }
67
68 #[test]
69 fn physical_cpus_positive() {
70 assert!(HardwareMaster::physical_cpus() >= 1, "物理核心数应 ≥ 1");
71 }
72
73 #[test]
74 fn parallel_process_preserves_order_and_len() {
75 let items: Vec<i32> = (0..100).collect();
76 let doubled = HardwareMaster::parallel_process(items.clone(), |x| x * 2);
77 assert_eq!(doubled.len(), 100);
78 assert_eq!(doubled, items.iter().map(|x| x * 2).collect::<Vec<_>>());
80 }
81
82 #[test]
83 fn parallel_process_empty() {
84 let out: Vec<i32> = HardwareMaster::parallel_process(Vec::new(), |x| x);
85 assert!(out.is_empty());
86 }
87}