Rust Tutorials: std::time (Duration, Instant)

beginner
15 min

Rust Tutorials: std::time (Duration, Instant)

Welcome to our Rust Tutorial on the std::time module! Today, we'll dive into the Duration and Instant types, which are essential for dealing with time in your Rust projects. Let's get started! 🎯

Understanding std::time

The std::time module is a part of the Rust standard library, providing functionality for measuring and working with time. It's a powerful tool for creating accurate, time-sensitive applications. 📝

The Duration Type

Duration is a type in the std::time module that represents a time interval. It can be used to measure and manipulate differences between two points in time. 💡

rust
use std::time::Duration; let five_seconds = Duration::from_secs(5);

In the example above, we create a Duration value named five_seconds that represents an interval of 5 seconds.

Creating a Duration from different units

Duration can be initialized using various units of time. Here's an example:

rust
use std::time::Duration; let two_hours = Duration::from_secs(7200); let ten_minutes = Duration::from_secs(600); let point_three_seconds = Duration::from_millis(300);

In this example, we create Duration values for 2 hours, 10 minutes, and 0.3 seconds.

The Instant Type

Instant is another type in the std::time module that represents a specific point in time on the system's clock. You can use it to measure elapsed time between two events. 💡

rust
use std::time::Instant; let start = Instant::now(); // Your code here let elapsed = start.elapsed();

In the example above, we create an Instant value named start at the current time, then measure the elapsed time between start and the current time using the elapsed() method.

Practical Example: Timer

Let's create a simple timer using Duration and Instant.

rust
use std::time::Instant; use std::thread; use std::time::Duration; fn main() { let five_seconds = Duration::from_secs(5); let start = Instant::now(); thread::spawn(|| { loop { let elapsed = Instant::now().duration_since(start); let seconds = elapsed.as_secs_f64(); if seconds >= 5.0 { break; } println!("{} seconds have passed.", seconds); thread::sleep(Duration::from_millis(1000)); } }); println!("The timer has started. Press Enter to stop it."); let _ = read_line(); } fn read_line() -> String { let mut input = String::new(); std::io::stdin().read_line(&mut input).expect("Error reading input"); input }

In this example, we create a timer that runs for 5 seconds, printing the elapsed time every second. Pressing Enter will stop the timer.

Quiz

Quick Quiz
Question 1 of 1

Which type represents a specific point in time on the system's clock?