throttler.go 1.1 KB

12345678910111213141516171819202122232425262728293031323334
  1. package util
  2. import "time"
  3. type WriteThrottler struct {
  4. compactionBytePerSecond int64
  5. lastSizeCounter int64
  6. lastSizeCheckTime time.Time
  7. }
  8. func NewWriteThrottler(bytesPerSecond int64) *WriteThrottler {
  9. return &WriteThrottler{
  10. compactionBytePerSecond: bytesPerSecond,
  11. lastSizeCheckTime: time.Now(),
  12. }
  13. }
  14. func (wt *WriteThrottler) MaybeSlowdown(delta int64) {
  15. if wt.compactionBytePerSecond > 0 {
  16. wt.lastSizeCounter += delta
  17. now := time.Now()
  18. elapsedDuration := now.Sub(wt.lastSizeCheckTime)
  19. if elapsedDuration > 100*time.Millisecond {
  20. overLimitBytes := wt.lastSizeCounter - wt.compactionBytePerSecond/10
  21. if overLimitBytes > 0 {
  22. overRatio := float64(overLimitBytes) / float64(wt.compactionBytePerSecond)
  23. sleepTime := time.Duration(overRatio*1000) * time.Millisecond
  24. // glog.V(0).Infof("currently %d bytes, limit to %d bytes, over by %d bytes, sleeping %v over %.4f", wt.lastSizeCounter, wt.compactionBytePerSecond/10, overLimitBytes, sleepTime, overRatio)
  25. time.Sleep(sleepTime)
  26. }
  27. wt.lastSizeCounter, wt.lastSizeCheckTime = 0, time.Now()
  28. }
  29. }
  30. }