Skip to content

Commit b3daed6

Browse files
committed
refactor: only fetch from the now object once
- only fetch from the chrono object once - operate on the returned timestamp in all subsequent math for performance and time drift mitigation
1 parent 11134b8 commit b3daed6

File tree

1 file changed

+10
-5
lines changed

1 file changed

+10
-5
lines changed

src/utils/calc.rs

Lines changed: 10 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -235,13 +235,18 @@ impl SlotCalculator {
235235
}
236236

237237
/// The current number of milliseconds into the slot.
238+
///
239+
/// Truncates the millisecond timestamp to seconds, then uses that to
240+
/// calculate the point within the slot, adding back the milliseconds
241+
/// remainder to the final result to provide millisecond precision.
238242
pub fn current_point_within_slot_ms(&self) -> Option<u64> {
239-
let now = chrono::Utc::now();
240-
let timestamp = now.timestamp() as u64;
241-
let millis = now.timestamp_subsec_millis() as u64;
243+
// NB: Only fetch from now() object once and reuse
244+
let timestamp_ms = chrono::Utc::now().timestamp_millis() as u64;
245+
let timestamp_s = timestamp_ms / 1000;
246+
let remainder = timestamp_ms - timestamp_s;
242247

243-
self.point_within_slot(timestamp)
244-
.map(|point| std::time::Duration::from_secs(point).as_millis() as u64 + millis)
248+
self.point_within_slot(timestamp_s)
249+
.map(|point| std::time::Duration::from_secs(point).as_millis() as u64 + remainder)
245250
}
246251

247252
/// Calculates the slot that starts at the given timestamp.

0 commit comments

Comments
 (0)