xref: /aosp_15_r20/external/crosvm/metrics/src/sys/windows/gpu_metrics.rs (revision bb4ee6a4ae7042d18b07a98463b9c8b875e44b39)
1 // Copyright 2022 The ChromiumOS Authors
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
4 
5 use std::sync::atomic::AtomicBool;
6 use std::sync::atomic::Ordering;
7 use std::sync::Arc;
8 
9 use crate::sys::system_metrics::CoreWinMetrics;
10 use crate::sys::windows::Error;
11 use crate::sys::windows::Result;
12 
13 static INSTANCE_EXISTS: AtomicBool = AtomicBool::new(false);
14 
15 /// Used by gpu_display to show metrics in the crosvm performance overlay.
16 pub struct Metrics {
17     metrics: Vec<Box<dyn ToString + Send + Sync>>,
18     // more_metrics is for metrics which have multiple owners (e.g., device dependent).
19     more_metrics: Vec<Arc<dyn ToString + Send + Sync>>,
20 }
21 
22 impl Metrics {
new() -> Result<Self>23     pub fn new() -> Result<Self> {
24         if INSTANCE_EXISTS
25             .compare_exchange(false, true, Ordering::SeqCst, Ordering::SeqCst)
26             .is_err()
27         {
28             return Err(Error::InstanceAlreadyExists);
29         }
30         Ok(Metrics {
31             metrics: vec![
32                 #[cfg(windows)]
33                 Box::new(CoreWinMetrics::new()?),
34             ],
35             more_metrics: vec![],
36         })
37     }
38 
add_gpu_metrics(&mut self, t: Arc<dyn ToString + Send + Sync>)39     pub fn add_gpu_metrics(&mut self, t: Arc<dyn ToString + Send + Sync>) {
40         self.more_metrics.push(t);
41     }
42 
get_metric_string(&self) -> String43     pub fn get_metric_string(&self) -> String {
44         let mut buf = String::new();
45         for collector in self.metrics.iter() {
46             buf.push_str(&collector.to_string());
47             buf.push('\n');
48         }
49         for collector in self.more_metrics.iter() {
50             buf.push_str(&collector.to_string());
51             buf.push('\n');
52         }
53         buf
54     }
55 }
56