Skip to content

Commit 3caa936

Browse files
committed
Improve precision of Duration-float operations
Rather than convert Duration to a float in order to multiply or divide by a floating point number, which entails a loss of precision, we instead represent both operands as u128 nanoseconds and perform integer arithmetic thereupon.
1 parent 1b9ae9e commit 3caa936

2 files changed

Lines changed: 187 additions & 6 deletions

File tree

‎library/core/src/time.rs‎

Lines changed: 159 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1020,7 +1020,76 @@ impl Duration {
10201020
without modifying the original"]
10211021
#[inline]
10221022
pub fn mul_f64(self, rhs: f64) -> Duration {
1023-
Duration::from_secs_f64(rhs * self.as_secs_f64())
1023+
const NUM_BITS_MANT: i32 = f64::MANTISSA_DIGITS as i32 - 1;
1024+
const NUM_BITS_EXP: i32 = 64 - f64::MANTISSA_DIGITS as i32;
1025+
1026+
const MANT_MASK: u64 = (1 << NUM_BITS_MANT) - 1;
1027+
const EXP_MASK: u64 = (1 << NUM_BITS_EXP) - 1;
1028+
const EXP_BIAS: i32 = 1 - (1 << NUM_BITS_EXP) / 2;
1029+
1030+
const DURATION_BITS: i32 = 64 + NANOS_PER_SEC.ilog2() as i32 + 1;
1031+
const {
1032+
assert!(DURATION_BITS < 128);
1033+
}
1034+
1035+
let rhs_raw = rhs.to_bits();
1036+
let mant_raw = rhs_raw & MANT_MASK;
1037+
let exp_raw = (rhs_raw >> NUM_BITS_MANT) & EXP_MASK;
1038+
1039+
if exp_raw == EXP_MASK {
1040+
panic!("result is not finite");
1041+
}
1042+
1043+
if self.is_zero() || (exp_raw == 0 && mant_raw == 0) {
1044+
// At least one factor is zero, so their product must be zero.
1045+
return Duration::ZERO;
1046+
}
1047+
1048+
let (mant, biased_exp) = if exp_raw == 0 {
1049+
// `rhs` is subnormal. Renormalize by shifting so that the highest set bit is
1050+
// in the correct leading bit position.
1051+
let shift = mant_raw.leading_zeros() as i32 - NUM_BITS_EXP;
1052+
(mant_raw << shift, 1 - shift)
1053+
} else {
1054+
// `rhs` is normal. Set the implied leading bit.
1055+
(mant_raw | (MANT_MASK + 1), exp_raw as i32)
1056+
};
1057+
1058+
// From this point on, consider `mant` to be an integer of `f64::MANTISSA_DIGITS` bits,
1059+
// rather than a normalized fraction; therefore adjust the exponent by `NUM_BITS_MANT`.
1060+
let exp = biased_exp + EXP_BIAS - NUM_BITS_MANT;
1061+
let mant = mant as u128;
1062+
1063+
if exp < -DURATION_BITS {
1064+
// `rhs` is such a small factor that it scales down any `Duration` to less than 0.5ns.
1065+
return Duration::ZERO;
1066+
}
1067+
1068+
if rhs.is_sign_negative() {
1069+
panic!("result is negative")
1070+
}
1071+
1072+
let lhs_nanos = self.as_nanos();
1073+
1074+
let nanos = if let Ok(exp) = u32::try_from(exp) {
1075+
// `exp` is non-negative, therefore `rhs` has no fractional part. Mere integer
1076+
// multiplication is sufficient.
1077+
mant.checked_shl(exp).and_then(|rhs_int| lhs_nanos.checked_mul(rhs_int))
1078+
} else {
1079+
// `exp` is negative, therefore `rhs` has both integer and fractional parts. In
1080+
// calculating the product for the former, incorporate any carry from the product of
1081+
// the latter.
1082+
let rhs_int = mant >> -exp;
1083+
let rhs_frac = mant << (128 + exp);
1084+
1085+
lhs_nanos.checked_mul(rhs_int).and_then(|product| {
1086+
let carry = lhs_nanos.carrying_mul(rhs_frac, 0).1;
1087+
product.checked_add(carry)
1088+
})
1089+
}
1090+
.expect("result overflows `Duration`");
1091+
1092+
Duration::from_nanos_u128(nanos)
10241093
}
10251094

10261095
/// Multiplies `Duration` by `f32`.
@@ -1033,15 +1102,15 @@ impl Duration {
10331102
/// use std::time::Duration;
10341103
///
10351104
/// let dur = Duration::new(2, 700_000_000);
1036-
/// assert_eq!(dur.mul_f32(3.14), Duration::new(8, 478_000_641));
1105+
/// assert_eq!(dur.mul_f32(3.14), Duration::new(8, 478_000_283));
10371106
/// assert_eq!(dur.mul_f32(3.14e5), Duration::new(847_800, 0));
10381107
/// ```
10391108
#[stable(feature = "duration_float", since = "1.38.0")]
10401109
#[must_use = "this returns the result of the operation, \
10411110
without modifying the original"]
10421111
#[inline]
10431112
pub fn mul_f32(self, rhs: f32) -> Duration {
1044-
Duration::from_secs_f32(rhs * self.as_secs_f32())
1113+
self.mul_f64(rhs.into())
10451114
}
10461115

10471116
/// Divides `Duration` by `f64`.
@@ -1062,7 +1131,91 @@ impl Duration {
10621131
without modifying the original"]
10631132
#[inline]
10641133
pub fn div_f64(self, rhs: f64) -> Duration {
1065-
Duration::from_secs_f64(self.as_secs_f64() / rhs)
1134+
const NUM_BITS_MANT: i32 = f64::MANTISSA_DIGITS as i32 - 1;
1135+
const NUM_BITS_EXP: i32 = 64 - f64::MANTISSA_DIGITS as i32;
1136+
1137+
const MANT_MASK: u64 = (1 << NUM_BITS_MANT) - 1;
1138+
const EXP_MASK: u64 = (1 << NUM_BITS_EXP) - 1;
1139+
const EXP_BIAS: i32 = 1 - (1 << NUM_BITS_EXP) / 2;
1140+
1141+
const DURATION_BITS: i32 = 64 + NANOS_PER_SEC.ilog2() as i32 + 1;
1142+
const {
1143+
assert!(DURATION_BITS < 128);
1144+
}
1145+
1146+
let rhs_raw = rhs.to_bits();
1147+
1148+
if rhs.is_nan() || rhs_raw << 1 == 0 {
1149+
// `rhs` is either NaN or zero.
1150+
panic!("result is not finite");
1151+
}
1152+
1153+
let mant_raw = rhs_raw & MANT_MASK;
1154+
let exp_raw = (rhs_raw >> NUM_BITS_MANT) & EXP_MASK;
1155+
1156+
if self.is_zero() || exp_raw == EXP_MASK {
1157+
// Dividend is zero and/or divisor is infinite.
1158+
return Duration::ZERO;
1159+
}
1160+
1161+
let (mant, biased_exp) = if exp_raw == 0 {
1162+
// `rhs` is subnormal. Renormalize by shifting so that the highest set bit is
1163+
// in the correct leading bit position.
1164+
let shift = mant_raw.leading_zeros() as i32 - NUM_BITS_EXP;
1165+
(mant_raw << shift, 1 - shift)
1166+
} else {
1167+
// `rhs` is normal. Set the implied leading bit.
1168+
(mant_raw | (MANT_MASK + 1), exp_raw as i32)
1169+
};
1170+
1171+
// From this point on, consider `mant` to be an integer of `f64::MANTISSA_DIGITS` bits,
1172+
// rather than a normalized fraction; therefore adjust the exponent by `NUM_BITS_MANT`.
1173+
let exp = biased_exp + EXP_BIAS - NUM_BITS_MANT;
1174+
let mant = mant as u128;
1175+
1176+
if exp > DURATION_BITS - NUM_BITS_MANT {
1177+
// `rhs` is such a large divisor that it scales down any `Duration` to less than 0.5ns.
1178+
return Duration::ZERO;
1179+
}
1180+
if exp < -DURATION_BITS {
1181+
// `rhs` is such a small divisor that it scales up any `Duration` to overflow.
1182+
panic!("result overflows `Duration`");
1183+
}
1184+
1185+
if rhs.is_sign_negative() {
1186+
panic!("result is negative")
1187+
}
1188+
1189+
let lhs_nanos = self.as_nanos();
1190+
1191+
let nanos = if let Ok(exp) = u32::try_from(exp) {
1192+
// `exp` is non-negative, therefore `rhs` has no fractional part. Mere integer
1193+
// division is sufficient.
1194+
lhs_nanos / (mant << exp)
1195+
} else {
1196+
// `exp` is negative, therefore `rhs` has both integer and fractional parts. Calculate
1197+
// its reciprocal, split into integer and fractional parts, then calculate the product
1198+
// for the former, incorporating any carry from the product of the latter.
1199+
const MAX: u128 = 1 << 127;
1200+
let recip = (MAX / mant) << 1;
1201+
1202+
let recip_int = recip >> (128 + exp);
1203+
let recip_frac = recip << -exp;
1204+
1205+
lhs_nanos
1206+
.checked_mul(recip_int)
1207+
.and_then(|product| {
1208+
let (frac, mut carry) = lhs_nanos.carrying_mul(recip_frac, 0);
1209+
// round up if required
1210+
if frac & MAX != 0 {
1211+
carry += 1;
1212+
}
1213+
product.checked_add(carry)
1214+
})
1215+
.expect("result overflows `Duration`")
1216+
};
1217+
1218+
Duration::from_nanos_u128(nanos)
10661219
}
10671220

10681221
/// Divides `Duration` by `f32`.
@@ -1077,15 +1230,15 @@ impl Duration {
10771230
/// let dur = Duration::new(2, 700_000_000);
10781231
/// // note that due to rounding errors result is slightly
10791232
/// // different from 0.859_872_611
1080-
/// assert_eq!(dur.div_f32(3.14), Duration::new(0, 859_872_580));
1233+
/// assert_eq!(dur.div_f32(3.14), Duration::new(0, 859_872_583));
10811234
/// assert_eq!(dur.div_f32(3.14e5), Duration::new(0, 8_599));
10821235
/// ```
10831236
#[stable(feature = "duration_float", since = "1.38.0")]
10841237
#[must_use = "this returns the result of the operation, \
10851238
without modifying the original"]
10861239
#[inline]
10871240
pub fn div_f32(self, rhs: f32) -> Duration {
1088-
Duration::from_secs_f32(self.as_secs_f32() / rhs)
1241+
self.div_f64(rhs.into())
10891242
}
10901243

10911244
/// Divides `Duration` by `Duration` and returns `f64`.

‎library/coretests/tests/time.rs‎

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -598,3 +598,31 @@ fn from_neg_zero() {
598598
assert_eq!(Duration::from_secs_f32(-0.0), Duration::ZERO);
599599
assert_eq!(Duration::from_secs_f64(-0.0), Duration::ZERO);
600600
}
601+
602+
#[test]
603+
fn precise_duration_fp_mul() {
604+
let d1 = Duration::from_nanos_u128(1 << 90);
605+
let d2 = Duration::from_nanos_u128(2 << 90);
606+
let d3 = Duration::from_nanos_u128(3 << 90);
607+
608+
assert_eq!(d1.mul_f32(1.0), d1);
609+
assert_eq!(d1.mul_f32(2.0), d2);
610+
assert_eq!(d1.mul_f32(3.0), d3);
611+
assert_eq!(d2.mul_f32(1.5), d3);
612+
613+
let _ = Duration::MAX.mul_f32(1.0);
614+
}
615+
616+
#[test]
617+
fn precise_duration_fp_div() {
618+
let d1 = Duration::from_nanos_u128(1 << 90);
619+
let d2 = Duration::from_nanos_u128(2 << 90);
620+
let d3 = Duration::from_nanos_u128(3 << 90);
621+
622+
assert_eq!(d1.div_f32(1.0), d1);
623+
assert_eq!(d2.div_f32(2.0), d1);
624+
assert_eq!(d3.div_f32(3.0), d1);
625+
assert_eq!(d3.div_f32(1.5), d2);
626+
627+
let _ = Duration::MAX.div_f32(1.0);
628+
}

0 commit comments

Comments
 (0)