Reduce time.Now calls
Vladimir Bauer
8 years ago
| 140 | 140 | } |
| 141 | 141 | select { |
| 142 | 142 | case b.ops <- func(s *state) { |
| 143 | next := time.Now() | |
| 143 | 144 | if s.current == 0 { |
| 144 | s.startTime = time.Now() | |
| 145 | s.blockStartTime = s.startTime | |
| 145 | s.startTime = next | |
| 146 | s.blockStartTime = next | |
| 147 | } else { | |
| 148 | now := time.Now() | |
| 149 | s.updateTimePerItemEstimate(n, now, next) | |
| 150 | s.timeElapsed = now.Sub(s.startTime) | |
| 146 | 151 | } |
| 147 | 152 | sum := s.current + int64(n) |
| 148 | s.timeElapsed = time.Since(s.startTime) | |
| 149 | s.updateTimePerItemEstimate(n) | |
| 150 | 153 | if s.total > 0 && sum >= s.total { |
| 151 | 154 | if s.dynamic { |
| 152 | 155 | sum -= sum * s.dropRatio / 100 |
| 157 | 160 | return |
| 158 | 161 | } |
| 159 | 162 | s.current = sum |
| 160 | s.blockStartTime = time.Now() | |
| 161 | 163 | }: |
| 162 | 164 | case <-b.quit: |
| 163 | 165 | } |
| 328 | 330 | return buf |
| 329 | 331 | } |
| 330 | 332 | |
| 331 | func (s *state) updateTimePerItemEstimate(amount int) { | |
| 332 | lastBlockTime := time.Since(s.blockStartTime) // shorthand for time.Now().Sub(t) | |
| 333 | func (s *state) updateTimePerItemEstimate(amount int, now, next time.Time) { | |
| 334 | lastBlockTime := now.Sub(s.blockStartTime) | |
| 333 | 335 | lastItemEstimate := float64(lastBlockTime) / float64(amount) |
| 334 | 336 | s.timePerItem = time.Duration((s.etaAlpha * lastItemEstimate) + (1-s.etaAlpha)*float64(s.timePerItem)) |
| 337 | s.blockStartTime = next | |
| 335 | 338 | } |
| 336 | 339 | |
| 337 | 340 | func (s *state) isFull() bool { |