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)
| 633 | // resolution. This function should be used if a difference of more than 290 years is |
| 634 | // possible between time values, and a microsecond resolution is acceptable. |
| 635 | func DiffMicros(t1, t2 time.Time) int64 { |
| 636 | micros := int64(0) |
| 637 | nanos := time.Duration(0) |
| 638 | for { |
| 639 | // time.Sub(time) can overflow for durations larger than ~290 years, so |
| 640 | // we need to perform this diff iteratively. If this method overflows, |
| 641 | // it will return either minTimeDuration or maxTimeDuration. |
| 642 | d := t1.Sub(t2) |
| 643 | overflow := d == minTimeDuration || d == maxTimeDuration |
| 644 | if d == minTimeDuration { |
| 645 | // We use -maxTimeDuration here because -minTimeDuration would overflow. |
| 646 | d = -maxTimeDuration |
| 647 | } |
| 648 | micros += int64(d / time.Microsecond) |
| 649 | nanos += d % time.Microsecond |
| 650 | if !overflow { |
| 651 | break |
| 652 | } |
| 653 | t1 = t1.Add(-d) |
| 654 | } |
| 655 | micros += int64(nanos / time.Microsecond) |
| 656 | nanoRem := nanos % time.Microsecond |
| 657 | if nanoRem >= time.Microsecond/2 { |
| 658 | micros++ |
| 659 | } else if nanoRem <= -time.Microsecond/2 { |
| 660 | micros-- |
| 661 | } |
| 662 | return micros |
| 663 | } |
| 664 | |
| 665 | // AddMicros adds the microsecond delta to the provided time value. The reason |
| 666 | // this function is necessary even though time.Add(duration) exists is that time.Duration |