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! 🎯
std::timeThe 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. 📝
Duration TypeDuration 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. 💡
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.
Duration from different unitsDuration can be initialized using various units of time. Here's an example:
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.
Instant TypeInstant 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. 💡
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.
Let's create a simple timer using Duration and Instant.
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.
Which type represents a specific point in time on the system's clock?