|
| 1 | +// Copyright 2019-2023 Tauri Programme within The Commons Conservancy |
| 2 | +// SPDX-License-Identifier: Apache-2.0 |
| 3 | +// SPDX-License-Identifier: MIT |
| 4 | + |
| 5 | +use std::time::Instant; |
| 6 | + |
| 7 | +// The TransferStats struct is used to track and calculate the transfer speed of data chunks over time. |
| 8 | +pub struct TransferStats { |
| 9 | + accumulated_chunk_len: usize, // Total length of chunks transferred in the current period |
| 10 | + accumulated_time: u128, // Total time taken for the transfers in the current period |
| 11 | + pub transfer_speed: u64, // Calculated transfer speed in bytes per second |
| 12 | + start_time: Instant, // Time when the current period started |
| 13 | + granularity: u32, // Time period (in milliseconds) over which the transfer speed is calculated |
| 14 | +} |
| 15 | + |
| 16 | +impl TransferStats { |
| 17 | + // Initializes a new TransferStats instance with the specified granularity. |
| 18 | + pub fn start(granularity: u32) -> Self { |
| 19 | + Self { |
| 20 | + accumulated_chunk_len: 0, |
| 21 | + accumulated_time: 0, |
| 22 | + transfer_speed: 0, |
| 23 | + start_time: Instant::now(), |
| 24 | + granularity, |
| 25 | + } |
| 26 | + } |
| 27 | + // Records the transfer of a data chunk and updates the transfer speed if the granularity period has elapsed. |
| 28 | + pub fn record_chunk_transfer(&mut self, chunk_len: usize) { |
| 29 | + let now = Instant::now(); |
| 30 | + let it_took = now.duration_since(self.start_time).as_millis(); |
| 31 | + self.accumulated_chunk_len += chunk_len; |
| 32 | + self.accumulated_time += it_took; |
| 33 | + |
| 34 | + // If the accumulated time exceeds the granularity, calculate the transfer speed. |
| 35 | + if self.accumulated_time >= self.granularity as u128 { |
| 36 | + self.transfer_speed = |
| 37 | + (self.accumulated_chunk_len as u128 / self.accumulated_time * 1024) as u64; |
| 38 | + self.accumulated_chunk_len = 0; |
| 39 | + self.accumulated_time = 0; |
| 40 | + } |
| 41 | + |
| 42 | + // Reset the start time for the next period. |
| 43 | + self.start_time = now; |
| 44 | + } |
| 45 | +} |
| 46 | + |
| 47 | +// Provides a default implementation for TransferStats with a granularity of 500 milliseconds. |
| 48 | +impl Default for TransferStats { |
| 49 | + fn default() -> Self { |
| 50 | + Self::start(500) // Default granularity is 500 |
| 51 | + } |
| 52 | +} |
0 commit comments