package monitor import ( "sync" "time" ) // SpeedTracker calculates transfer rates by diffing byte counters. type SpeedTracker struct { mu sync.Mutex lastIn int64 lastOut int64 lastTime time.Time downRate float64 upRate float64 } // NewSpeedTracker creates a new speed tracker. func NewSpeedTracker() *SpeedTracker { return &SpeedTracker{} } // Update records new byte counters and calculates rates. func (s *SpeedTracker) Update(inBytes, outBytes int64) { s.mu.Lock() defer s.mu.Unlock() now := time.Now() if !s.lastTime.IsZero() { dt := now.Sub(s.lastTime).Seconds() if dt > 0 { s.downRate = float64(inBytes-s.lastIn) / dt s.upRate = float64(outBytes-s.lastOut) / dt if s.downRate < 0 { s.downRate = 0 } if s.upRate < 0 { s.upRate = 0 } } } s.lastIn = inBytes s.lastOut = outBytes s.lastTime = now } // Rates returns the current download and upload rates in bytes/sec. func (s *SpeedTracker) Rates() (down, up float64) { s.mu.Lock() defer s.mu.Unlock() return s.downRate, s.upRate }