Skip to main content

wasmedge_sdk/
statistics.rs

1//! Defines WasmEdge Statistics struct.
2
3use crate::WasmEdgeResult;
4use wasmedge_sys as sys;
5
6/// Used to collect statistics of the WasmEdge runtime, such as the count of instructions in execution.
7#[derive(Debug, Clone)]
8pub struct Statistics {
9    pub(crate) inner: sys::Statistics,
10}
11impl Statistics {
12    /// Creates a new [Statistics].
13    ///
14    /// # Error
15    ///
16    /// If fail to create a [Statistics], then an error is returned.
17    pub fn new() -> WasmEdgeResult<Self> {
18        let inner = sys::Statistics::create()?;
19        Ok(Self { inner })
20    }
21
22    /// Returns the instruction count in execution.
23    pub fn count(&self) -> u64 {
24        self.inner.instr_count()
25    }
26
27    /// Returns the instruction count per second in execution.
28    ///
29    /// # Notice
30    ///
31    /// For the following cases,
32    /// - [Statistics] is not enabled, or
33    /// - the total execution time is 0
34    ///
35    /// The instructions per second could be `NaN`, which represents `divided-by-zero`.
36    /// Use the `is_nan` function of F64 to check the return value before use it,
37    /// for example,
38    ///
39    /// ```
40    /// use wasmedge_sdk::Statistics;
41    ///
42    /// // create a Statistics instance
43    /// let stat = Statistics::new().expect("fail to create a Statistics");
44    ///
45    /// // check instruction count per second
46    /// assert!(stat.count_per_second().is_nan());
47    /// ```
48    pub fn count_per_second(&self) -> f64 {
49        self.inner.instr_per_sec()
50    }
51
52    /// Returns the total cost in execution.
53    pub fn cost(&self) -> u64 {
54        self.inner.cost_in_total()
55    }
56
57    /// Sets the cost of instructions.
58    ///
59    /// # Arguments
60    ///
61    /// - `cost_table` specifies the slice of cost table.
62    pub fn set_cost_table(&mut self, cost_table: impl AsRef<[u64]>) {
63        self.inner.set_cost_table(cost_table)
64    }
65
66    /// Sets the cost limit in execution.
67    ///
68    /// # Arguments
69    ///
70    /// - `limit` specifies the cost limit.
71    pub fn set_cost_limit(&mut self, limit: u64) {
72        self.inner.set_cost_limit(limit)
73    }
74}