You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

34 lines
1.1 KiB

  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. }