kernel/time.rs
1//! Time utilities for the kernel
2//!
3//! This module provides time-related functionality for the kernel,
4//! including current time access for filesystem operations.
5
6use crate::timer::get_kernel_timer;
7
8/// Get the current time in microseconds
9///
10/// This function returns the current system time in microseconds since boot.
11/// For filesystem operations, this provides a monotonic timestamp.
12pub fn current_time() -> u64 {
13 // For now, use CPU 0's timer. In a multi-core system, this might need
14 // to be more sophisticated to get a consistent global timestamp.
15 get_kernel_timer().get_time_us(0)
16}
17
18/// Get the current time in milliseconds
19pub fn current_time_ms() -> u64 {
20 current_time() / 1000
21}
22
23/// Get the current time in seconds
24pub fn current_time_s() -> u64 {
25 current_time() / 1_000_000
26}
27
28/// Get the current time in nanoseconds
29///
30/// This function returns the current system time in nanoseconds since boot.
31/// Useful for high-resolution timestamps in input events and profiling.
32pub fn current_time_ns() -> u64 {
33 current_time() * 1000
34}
35
36/// Convert microseconds to a human-readable format (for debugging)
37pub fn format_time_us(time_us: u64) -> (u64, u64, u64) {
38 let seconds = time_us / 1_000_000;
39 let minutes = seconds / 60;
40 let hours = minutes / 60;
41
42 (hours, minutes % 60, seconds % 60)
43}
44
45#[cfg(test)]
46mod tests {
47 use super::*;
48
49 #[test_case]
50 fn test_format_time() {
51 let (hours, minutes, seconds) = format_time_us(3_661_000_000); // 1 hour, 1 minute, 1 second
52 assert_eq!(hours, 1);
53 assert_eq!(minutes, 1);
54 assert_eq!(seconds, 1);
55
56 let (hours, minutes, seconds) = format_time_us(123_000_000); // 2 minutes, 3 seconds
57 assert_eq!(hours, 0);
58 assert_eq!(minutes, 2);
59 assert_eq!(seconds, 3);
60 }
61}