Measuring the time duration of a function is a common task in software programming which allows you to determine the possible performance bottlenecks. This can, in turn, help you optimize your code and identify the performance issues.
One significant way to determine your code’s performance is to calculate the execution time of a specific function. This can be useful when working with complex algorithms or large data sets where even a slight improvement in execution time can significantly impact the application’s overall performance.
In this tutorial, we will discuss one basic and simple function in the Rust programming language that allows us to determine the execution time of a given function.
Rust Time Module
In Rust, we can use the std::time::Instant module to determine the performance of a given function.
The module provides us with the now() function to get the current time. We can then use this function to determine the start and end time before and at the end of function execution.
Example:
The following example demonstrates how we can use this method to calculate the execution time of a function that sorts an input vector:
fn sort_vector(vec: &mut Vec<i32>) {
vec.sort();
}
fn main() {
let mut vec = vec![3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5];
println!("Unsorted vector: {:?}", vec);
let start = Instant::now();
sort_vector(&mut vec);
let duration = start.elapsed();
println!("Sorted vector: {:?}", vec);
println!("Execution time: {:?}", duration);
}
In this example, the sort_vector() function takes a mutable reference to a vector of i32 values and sorts it in place using the built-in sort() method.
The main() function creates a random vector, prints it to the console, and then measures the execution time of sort_vector() using Instant. Then, we print the duration to the console along with the sorted vector.
Running the previous code should print the following:
Sorted vector: [1, 1, 2, 3, 3, 4, 5, 5, 5, 6, 9]
Execution time: 5.4µs
The provided code should return the execution time of the function.
Conclusion
In this tutorial, we explored how we can use the Rust time command to measure the execution time of a given function. It is good to keep in mind that this is not an efficient method of benchmarking a given program. Consider the tools and crates that are built for performance benchmarking.