You're right! The Rust version I gave requires the caller to wrap the function call and its arguments in a closure, which is less ergonomic than the C++ version that accepts a function and its arguments separately.
Rust doesn't have variadic generics yet, so we can't directly write a function that takes a callable and arbitrary arguments like in C++. However, we can simulate this behavior using a macro or by using tuples and traits.
Solution 1: Using a macro (most ergonomic)
We can write a macro that takes a function and its arguments, calls the function with those arguments, and times the call.
use std::time::Instant;
macro_rules! time_function_call {
($func:expr $(, $args:expr)* $(,)?) => {{
let start = Instant::now();
let result = $func($($args),*);
let duration = start.elapsed();
(result, duration.as_millis())
}};
}
// Example functions
fn add(a: i32, b: i32) -> i32 {
a + b
}
fn main() {
let (result, time_ms) = time_function_call!(add, 5, 7);
println!("Result: {}, Time: {} ms", result, time_ms);
}
Explanation:
- The macro
time_function_call! takes a function expression and zero or more arguments.
- It calls the function with the provided arguments and times the call.
- Returns a tuple
(result, elapsed_time_in_millis).
Solution 2: Using a trait and tuple unpacking (more complex)
Rust doesn't have built-in tuple unpacking for function arguments, but we can implement a trait to simulate this. This is more advanced and verbose, but I'll show a minimal example for up to 3 arguments.
use std::time::Instant;
// Trait to call a function with a tuple of arguments
trait Call<Args> {
type Output;
fn call(self, args: Args) -> Self::Output;
}
// Implement Call for functions with 0 arguments
impl<R, F> Call<()> for F
where
F: FnOnce() -> R,
{
type Output = R;
fn call(self, _args: ()) -> R {
self()
}
}
// Implement Call for functions with 1 argument
impl<R, F, A1> Call<(A1,)> for F
where
F: FnOnce(A1) -> R,
{
type Output = R;
fn call(self, args: (A1,)) -> R {
self(args.0)
}
}
// Implement Call for functions with 2 arguments
impl<R, F, A1, A2> Call<(A1, A2)> for F
where
F: FnOnce(A1, A2) -> R,
{
type Output = R;
fn call(self, args: (A1, A2)) -> R {
self(args.0, args.1)
}
}
// Implement Call for functions with 3 arguments (add more if needed)
impl<R, F, A1, A2, A3> Call<(A1, A2, A3)> for F
where
F: FnOnce(A1, A2, A3) -> R,
{
type Output = R;
fn call(self, args: (A1, A2, A3)) -> R {
self(args.0, args.1, args.2)
}
}
// The timing function
fn time_function_call<F, Args>(func: F, args: Args) -> (F::Output, u128)
where
F: Call<Args>,
{
let start = Instant::now();
let result = func.call(args);
let duration = start.elapsed();
(result, duration.as_millis())
}
// Example usage
fn add(a: i32, b: i32) -> i32 {
a + b
}
fn main() {
let (result, time_ms) = time_function_call(add, (5, 7));
println!("Result: {}, Time: {} ms", result, time_ms);
let (result0, time0) = time_function_call(|| 42, ());
println!("Result: {}, Time: {} ms", result0, time0);
}