Apparently, there is some bad advice using chrono
out there on benchmarking functions in Rust aka calculating time difference between two points. Measuring the time elapsed between two points in the source code to e.g. benchmark functions is straight forward using std::time
. chrono
is not needed for that.
Let’s start with the bad example using chrono
:
use chrono::Utc;
// ...
let start = Utc::now::now().time();
// do some computation
let end = Utc::now::now().time();
let dt = end - start;
let dt_ns = dt.num_nanoseconds().unwrap();
// ...
This approach uses timestamps based on the system clock meaning if it is changed, e.g. running it accidentally when daylight savings time starts, it will mess up the measurement. Yes, there exists software that runs for more than a couple of seconds per function call ;).
A better way without additional dependencies which need to be downloaded and compiled is to use std::time
. std::time
is monotonic and not affected by a change of the system clock.
use std::time::{Duration, Instant};
// ...
let start_marker = Instant.now();
// do some computation
let dt_s = start_marker.elapsed();
// ...
Calling .elapsed()
returns a struct of type std::time::Duration
which is a floating point number of seconds with nanosecond level precision if the underlying system provides such resolution.