Skip to content

Commit

Permalink
Improve the Correctness & Performance of Time Formatting (#576)
Browse files Browse the repository at this point in the history
This improves the correctness and the performance of the time formatting
by making use of the fact that the underlying times are represented as a
pair of integers (seconds and the subsecond nanoseconds). This way
instead of formatting the fractional part as a floating point number we
already have the fractional part in form of the nanoseconds. On top of
that we can improve the performance a little bit by removing the data
dependency we introduced by calculating the hours from the total minutes
(and so on) when we can just calculate the hours directly from the total
seconds. This allows for a little bit of instruction level parallelism
where the days, hours, minutes and seconds can all be calculated in
parallel.
  • Loading branch information
CryZe authored Oct 5, 2022
1 parent 7891019 commit 66fab23
Show file tree
Hide file tree
Showing 12 changed files with 163 additions and 184 deletions.
1 change: 1 addition & 0 deletions crates/livesplit-auto-splitting/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -127,4 +127,5 @@ mod runtime;
mod timer;

pub use runtime::{CreationError, InterruptHandle, RunError, Runtime};
pub use time;
pub use timer::{Timer, TimerState};
6 changes: 3 additions & 3 deletions src/analysis/skill_curve.rs
Original file line number Diff line number Diff line change
Expand Up @@ -219,7 +219,7 @@ fn interpolate(
(weight_right, time_right): (f64, TimeSpan),
) -> TimeSpan {
let weight_diff_recip = (weight_right - weight_left).recip();
let perc_down = (weight_right - perc) * time_left.total_milliseconds() * weight_diff_recip;
let perc_up = (perc - weight_left) * time_right.total_milliseconds() * weight_diff_recip;
TimeSpan::from_milliseconds(perc_up + perc_down)
let perc_down = (weight_right - perc) * time_left.total_seconds() * weight_diff_recip;
let perc_up = (perc - weight_left) * time_right.total_seconds() * weight_diff_recip;
TimeSpan::from_seconds(perc_up + perc_down)
}
16 changes: 0 additions & 16 deletions src/platform/math.rs
Original file line number Diff line number Diff line change
@@ -1,17 +1,5 @@
cfg_if::cfg_if! {
if #[cfg(feature = "std")] {
pub mod f64 {
#[inline(always)]
pub fn abs(x: f64) -> f64 {
x.abs()
}

#[inline(always)]
pub fn floor(x: f64) -> f64 {
x.floor()
}
}

pub mod f32 {
#[inline(always)]
pub fn abs(x: f32) -> f32 {
Expand All @@ -24,10 +12,6 @@ cfg_if::cfg_if! {
}
}
} else {
pub mod f64 {
pub use libm::{fabs as abs, floor};
}

pub mod f32 {
pub use libm::{fabsf as abs, powf};
}
Expand Down
27 changes: 8 additions & 19 deletions src/timing/formatter/accuracy.rs
Original file line number Diff line number Diff line change
Expand Up @@ -15,41 +15,30 @@ pub enum Accuracy {
}

impl Accuracy {
/// Formats the seconds provided with the chosen accuracy. If there should
/// be a zero prefix, the seconds are prefixed with a 0, if they are less
/// than 10s.
pub const fn format_seconds(self, seconds: f64, zero_prefix: bool) -> FormattedSeconds {
/// Formats the nanoseconds provided with the chosen accuracy.
pub const fn format_nanoseconds(self, nanoseconds: u32) -> FormattedSeconds {
FormattedSeconds {
accuracy: self,
seconds,
zero_prefix,
nanoseconds,
}
}
}

use super::{extract_hundredths, extract_milliseconds, extract_tenths};
use core::fmt::{Display, Formatter, Result};

#[derive(Debug, PartialEq, Copy, Clone)]
#[derive(Debug, PartialEq, Eq, Copy, Clone)]
pub struct FormattedSeconds {
accuracy: Accuracy,
seconds: f64,
zero_prefix: bool,
nanoseconds: u32,
}

impl Display for FormattedSeconds {
fn fmt(&self, f: &mut Formatter<'_>) -> Result {
let s = self.seconds as u8;
if self.zero_prefix {
write!(f, "{s:02}")?;
} else {
write!(f, "{s}")?;
}
match self.accuracy {
Accuracy::Seconds => Ok(()),
Accuracy::Tenths => write!(f, ".{}", extract_tenths(self.seconds)),
Accuracy::Hundredths => write!(f, ".{:02}", extract_hundredths(self.seconds)),
Accuracy::Milliseconds => write!(f, ".{:03}", extract_milliseconds(self.seconds)),
Accuracy::Tenths => write!(f, ".{}", self.nanoseconds / 100_000_000),
Accuracy::Hundredths => write!(f, ".{:02}", self.nanoseconds / 10_000_000),
Accuracy::Milliseconds => write!(f, ".{:03}", self.nanoseconds / 1_000_000),
}
}
}
48 changes: 26 additions & 22 deletions src/timing/formatter/complete.rs
Original file line number Diff line number Diff line change
@@ -1,25 +1,25 @@
use super::{TimeFormatter, ASCII_MINUS};
use super::{TimeFormatter, ASCII_MINUS, SECONDS_PER_DAY, SECONDS_PER_HOUR, SECONDS_PER_MINUTE};
use crate::TimeSpan;
use core::fmt::{Display, Formatter, Result};

pub struct Inner(Option<TimeSpan>);

/// The Complete Time Formatter formats Time Spans in a way that preserves as
/// much information as possible. The hours and minutes are always shown and a
/// fractional part of 7 digits is used. If there's >24h, then a day prefix is
/// attached (with the hours wrapping around to 0): `dd.hh:mm:ss.fffffff`
/// fractional part of 9 digits is used. If there's >24h, then a day prefix is
/// attached (with the hours wrapping around to 0): `dd.hh:mm:ss.fffffffff`
///
/// This formatter uses an ASCII minus for negative times and shows a zero time
/// for empty times.
///
/// # Example Formatting
///
/// * Empty Time `00:00:00.0000000`
/// * Seconds `00:00:23.1234000`
/// * Minutes `00:12:34.9876543`
/// * Hours `12:34:56.1234567`
/// * Negative Times `-12:34:56.1234567`
/// * Days `89.12:34:56.1234567`
/// * Empty Time `00:00:00.000000000`
/// * Seconds `00:00:23.123400000`
/// * Minutes `00:12:34.987654321`
/// * Hours `12:34:56.123456789`
/// * Negative Times `-12:34:56.123456789`
/// * Days `89.12:34:56.123456789`
#[derive(Default)]
pub struct Complete;

Expand All @@ -44,25 +44,29 @@ impl TimeFormatter<'_> for Complete {
impl Display for Inner {
fn fmt(&self, f: &mut Formatter<'_>) -> Result {
if let Some(time) = self.0 {
let mut total_seconds = time.total_seconds();
if total_seconds < 0.0 {
total_seconds *= -1.0;
let (total_seconds, nanoseconds) = time.to_seconds_and_subsec_nanoseconds();
let (total_seconds, nanoseconds) = if total_seconds < 0 {
// Since, this Formatter is used for writing out split files, we
// have to use an ASCII Minus here.
write!(f, "{ASCII_MINUS}")?;
}
let seconds = total_seconds % 60.0;
let total_minutes = (total_seconds / 60.0) as u64;
let minutes = total_minutes % 60;
let total_hours = total_minutes / 60;
let hours = total_hours % 24;
let days = total_hours / 24;
f.write_str(ASCII_MINUS)?;
((-total_seconds) as u64, (-nanoseconds) as u32)
} else {
(total_seconds as u64, nanoseconds as u32)
};
// These are intentionally not data dependent, such that the CPU can
// calculate all of them in parallel. On top of that they are
// integer divisions of known constants, which get turned into
// multiplies and shifts, which is very fast.
let seconds = total_seconds % SECONDS_PER_MINUTE;
let minutes = (total_seconds % SECONDS_PER_HOUR) / SECONDS_PER_MINUTE;
let hours = (total_seconds % SECONDS_PER_DAY) / SECONDS_PER_HOUR;
let days = total_seconds / SECONDS_PER_DAY;
if days > 0 {
write!(f, "{days}.")?;
}
write!(f, "{hours:02}:{minutes:02}:{seconds:010.7}")
write!(f, "{hours:02}:{minutes:02}:{seconds:02}.{nanoseconds:09}")
} else {
write!(f, "00:00:00.0000000")
f.write_str("00:00:00.000000000")
}
}
}
33 changes: 18 additions & 15 deletions src/timing/formatter/days.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
use super::{TimeFormatter, MINUS};
use super::{TimeFormatter, MINUS, SECONDS_PER_DAY, SECONDS_PER_HOUR, SECONDS_PER_MINUTE};
use crate::TimeSpan;
use core::fmt::{Display, Formatter, Result};

Expand Down Expand Up @@ -43,30 +43,33 @@ impl TimeFormatter<'_> for Days {
impl Display for Inner {
fn fmt(&self, f: &mut Formatter<'_>) -> Result {
if let Some(time) = self.time {
let mut total_seconds = time.total_seconds();
if total_seconds < 0.0 {
total_seconds *= -1.0;
write!(f, "{MINUS}")?;
}
let total_seconds = total_seconds as u64;
let seconds = total_seconds % 60;
let total_minutes = total_seconds / 60;
let minutes = total_minutes % 60;
let total_hours = total_minutes / 60;
let hours = total_hours % 24;
let days = total_hours / 24;
let total_seconds = time.to_duration().whole_seconds();
let total_seconds = if total_seconds < 0 {
f.write_str(MINUS)?;
(-total_seconds) as u64
} else {
total_seconds as u64
};
// These are intentionally not data dependent, such that the CPU can
// calculate all of them in parallel. On top of that they are
// integer divisions of known constants, which get turned into
// multiplies and shifts, which is very fast.
let seconds = total_seconds % SECONDS_PER_MINUTE;
let minutes = (total_seconds % SECONDS_PER_HOUR) / SECONDS_PER_MINUTE;
let hours = (total_seconds % SECONDS_PER_DAY) / SECONDS_PER_HOUR;
let days = total_seconds / SECONDS_PER_DAY;

if days > 0 {
write!(f, "{days}d ")?;
}

if total_hours > 0 {
if days > 0 || hours > 0 {
write!(f, "{hours}:{minutes:02}:{seconds:02}")
} else {
write!(f, "{minutes}:{seconds:02}")
}
} else {
write!(f, "0:00")
f.write_str("0:00")
}
}
}
61 changes: 29 additions & 32 deletions src/timing/formatter/delta.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
use super::{Accuracy, TimeFormatter, DASH, MINUS, PLUS};
use super::{Accuracy, TimeFormatter, DASH, MINUS, PLUS, SECONDS_PER_HOUR, SECONDS_PER_MINUTE};
use crate::TimeSpan;
use core::fmt::{Display, Formatter, Result};

Expand Down Expand Up @@ -71,42 +71,39 @@ impl TimeFormatter<'_> for Delta {
impl Display for Inner {
fn fmt(&self, f: &mut Formatter<'_>) -> Result {
if let Some(time) = self.time {
let mut total_seconds = time.total_seconds();
if total_seconds < 0.0 {
total_seconds *= -1.0;
write!(f, "{MINUS}")?;
let (total_seconds, nanoseconds) = time.to_seconds_and_subsec_nanoseconds();
let (total_seconds, nanoseconds) = if total_seconds < 0 {
f.write_str(MINUS)?;
((-total_seconds) as u64, (-nanoseconds) as u32)
} else {
write!(f, "{PLUS}")?;
}
let seconds = total_seconds % 60.0;
let total_minutes = (total_seconds / 60.0) as u64;
let minutes = total_minutes % 60;
let hours = total_minutes / 60;
f.write_str(PLUS)?;
(total_seconds as u64, nanoseconds as u32)
};
// These are intentionally not data dependent, such that the CPU can
// calculate all of them in parallel. On top of that they are
// integer divisions of known constants, which get turned into
// multiplies and shifts, which is very fast.
let seconds = total_seconds % SECONDS_PER_MINUTE;
let minutes = (total_seconds % SECONDS_PER_HOUR) / SECONDS_PER_MINUTE;
let hours = total_seconds / SECONDS_PER_HOUR;
if hours > 0 {
if self.drop_decimals {
write!(f, "{hours}:{minutes:02}:{:02}", seconds as u8)
} else {
write!(
f,
"{hours}:{minutes:02}:{}",
self.accuracy.format_seconds(seconds, true)
)
}
} else if total_minutes > 0 {
if self.drop_decimals {
write!(f, "{minutes}:{:02}", seconds as u8)
} else {
write!(
f,
"{minutes}:{}",
self.accuracy.format_seconds(seconds, true)
)
}
write!(f, "{hours}:{minutes:02}:{seconds:02}")?;
} else if minutes > 0 {
write!(f, "{minutes}:{seconds:02}")?;
} else {
return write!(
f,
"{seconds}{}",
self.accuracy.format_nanoseconds(nanoseconds)
);
}
if !self.drop_decimals {
write!(f, "{}", self.accuracy.format_nanoseconds(nanoseconds))
} else {
write!(f, "{}", self.accuracy.format_seconds(seconds, false))
Ok(())
}
} else {
write!(f, "{DASH}")
f.write_str(DASH)
}
}
}
22 changes: 5 additions & 17 deletions src/timing/formatter/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -35,11 +35,8 @@ pub use self::{
regular::Regular, segment_time::SegmentTime,
};

use crate::{
platform::math::f64::{abs, floor},
TimeSpan,
};
use core::{cmp::min, fmt::Display};
use crate::TimeSpan;
use core::fmt::Display;

/// Time Formatters can be used to format optional Time Spans in various ways.
pub trait TimeFormatter<'a> {
Expand All @@ -53,7 +50,6 @@ pub trait TimeFormatter<'a> {
T: Into<Option<TimeSpan>>;
}

const EPSILON: f64 = 0.000_000_1;
/// The dash symbol to use for generic dashes in text.
pub const DASH: &str = "—";
/// The minus symbol to use for negative numbers.
Expand All @@ -64,14 +60,6 @@ pub const ASCII_MINUS: &str = "-";
/// The plus symbol to use for positive numbers.
pub const PLUS: &str = "+";

fn extract_tenths(seconds: f64) -> u8 {
min(9, floor((abs(seconds) % 1.0) * 10.0 + EPSILON) as u8)
}

fn extract_hundredths(seconds: f64) -> u8 {
min(99, floor((abs(seconds) % 1.0) * 100.0 + EPSILON) as u8)
}

fn extract_milliseconds(seconds: f64) -> u16 {
min(999, floor((abs(seconds) % 1.0) * 1000.0 + EPSILON) as u16)
}
const SECONDS_PER_MINUTE: u64 = 60;
const SECONDS_PER_HOUR: u64 = 60 * SECONDS_PER_MINUTE;
const SECONDS_PER_DAY: u64 = 24 * SECONDS_PER_HOUR;
Loading

0 comments on commit 66fab23

Please sign in to comment.