Substract from Duration


I'm trying to setup a sleep to target 60fps in my program. I do the following:

        let last_tick_duration = Duration::from_millis(self.last_tick.elapsed().unwrap_or(Duration::from_millis(0)).as_millis() as u64);
        let duration_16 = Duration::from_millis(16);
        if last_tick_duration > duration_16 {  // target is ~60fps
            std::thread::sleep(duration_16 - last_tick_duration);  // error here
        self.last_tick = SystemTime::now();

But it result:

thread 'main' panicked at 'overflow when subtracting durations', library/core/src/

And I fail to make a small reproducible code (when I do it there is no error...):

use std::time::{Duration, SystemTime};

fn main() {
    let now = SystemTime::now();
    let elapsed = now.elapsed().unwrap();
    let duration_16 = Duration::from_millis(16);
    if elapsed > duration_16 {
        println!("{:?}", duration_16 - elapsed);

I don't understand what is wrong with my code. Any help ? :slight_smile:

Did you mean to compare the other way? i.e. last_tick_duration < duration_16

As is, you're subtracting with a right-hand side that you just proved is greater than the left, which would always be negative if durations were signed.

Your smaller example never fails because elapsed will be very small, unlikely ever greater than 16ms, so it's not reaching that printed subtraction at all.

Oh you're right ! But with this comparison i never be over 16ms. I have something wrong i my code.

Thanks for your help !

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.