Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get timestamp in nanosecond (or anything close to that) in rust?

Tags:

rust

I need to add a timestamp to the data i collect, the data is collect quite fast, so second and milisecond based timestamp can't do the job well. I'm looking into nanosecond timestamp so how to get timestamp in nanosecond in rust?

Edit: I want a timestamp that is monotonic, and increase at a very fast rate, since the data collection is quite fast and every record need a timestamp.

like image 311
William Taylor Avatar asked Sep 07 '25 13:09

William Taylor


1 Answers

There's no such direct function but you can get the number of nanoseconds elapsed since Unix Epoch with SystemTime and Duration:

use std::time::{Duration, SystemTime};
let duration_since_epoch = SystemTime::now().duration_since(SystemTime::UNIX_EPOCH).unwrap();
let timestamp_nanos = duration_since_epoch.as_nanos(); // u128

If you need nanoseconds, you probably don't need them as an absolute timestamp though. It's probable you don't want a timestamp but a duration compared to an Instant.

like image 157
Denys Séguret Avatar answered Sep 10 '25 06:09

Denys Séguret