DiffMicros computes the microsecond difference between two time values. The reason this function is necessary even though time.Sub(time) exists is that time.Duration can only hold values up to ~290 years, because it stores duration at the nanosecond resolution. This function should be used if a diff
(t1, t2 time.Time)
| 608 | // resolution. This function should be used if a difference of more than 290 years is |
| 609 | // possible between time values, and a microsecond resolution is acceptable. |
| 610 | func DiffMicros(t1, t2 time.Time) int64 { |
| 611 | micros := int64(0) |
| 612 | nanos := time.Duration(0) |
| 613 | for { |
| 614 | // time.Sub(time) can overflow for durations larger than ~290 years, so |
| 615 | // we need to perform this diff iteratively. If this method overflows, |
| 616 | // it will return either minTimeDuration or maxTimeDuration. |
| 617 | d := t1.Sub(t2) |
| 618 | overflow := d == minTimeDuration || d == maxTimeDuration |
| 619 | if d == minTimeDuration { |
| 620 | // We use -maxTimeDuration here because -minTimeDuration would overflow. |
| 621 | d = -maxTimeDuration |
| 622 | } |
| 623 | micros += int64(d / time.Microsecond) |
| 624 | nanos += d % time.Microsecond |
| 625 | if !overflow { |
| 626 | break |
| 627 | } |
| 628 | t1 = t1.Add(-d) |
| 629 | } |
| 630 | micros += int64(nanos / time.Microsecond) |
| 631 | nanoRem := nanos % time.Microsecond |
| 632 | if nanoRem >= time.Microsecond/2 { |
| 633 | micros++ |
| 634 | } else if nanoRem <= -time.Microsecond/2 { |
| 635 | micros-- |
| 636 | } |
| 637 | return micros |
| 638 | } |
| 639 | |
| 640 | // AddMicros adds the microsecond delta to the provided time value. The reason |
| 641 | // this function is necessary even though time.Add(duration) exists is that time.Duration |