Re: [PATCH v1] rust: time: Avoid 64-bit integer division

From: Boqun Feng
Date: Thu May 01 2025 - 09:12:19 EST


On Thu, May 01, 2025 at 10:07:17PM +0900, FUJITA Tomonori wrote:
> On Thu, 1 May 2025 05:26:54 -0700
> Boqun Feng <boqun.feng@xxxxxxxxx> wrote:
>
> > On Thu, May 01, 2025 at 10:58:18AM +0900, FUJITA Tomonori wrote:
> >> Avoid 64-bit integer division that 32-bit architectures don't
> >> implement generally. This uses ktime_to_ms() and ktime_to_us()
> >> instead.
> >>
> >> The timer abstraction needs i64 / u32 division so C's div_s64() can be
> >> used but ktime_to_ms() and ktime_to_us() provide a simpler solution
> >> for this timer abstraction problem. On some architectures, there is
> >> room to optimize the implementation of them, but such optimization can
> >> be done if and when it becomes necessary.
> >>
> >
> > Nacked-by: Boqun Feng <boqun.feng@xxxxxxxxx>
> >
> > As I said a few times, we should rely on compiler's optimization when
> > available, i.e. it's a problem that ARM compiler doesn't have this
> > optimization, don't punish other architecture of no reason.
>
> Did you mean that we should do something like the following?
>

Yes, or

#[cfg(CONFIG_ARM)]
fn ns_to_ms(ns: i64) -> i64 {
// SAFETY: It is always safe to call `ktime_to_ms()` with any value.
unsafe { bindings::ktime_to_ms(self.nanos) }
}

#[cfg(not(CONFIG_ARM))]
fn ns_to_ms(ns: i64) -> i64 {
self.as_nanos() / NSEC_PER_MSEC
}

pub fn as_millis(self) -> i64 {
ns_to_ms(self.as_nanos())
}

Regards,
Boqun

> pub fn as_millis(self) -> i64 {
> #[cfg(CONFIG_ARM)]
> {
> // SAFETY: It is always safe to call `ktime_to_ms()` with any value.
> unsafe { bindings::ktime_to_ms(self.nanos) }
> }
> #[cfg(not(CONFIG_ARM))]
> {
> self.as_nanos() / NSEC_PER_MSEC
> }
> }
>