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