I have a function in Rust (that I did not write) which either returns in milliseconds or grinds for ~10 minutes before failing.
I would like to wrap the call to this function in something that returns an Option
which is None
if it takes over 10 seconds to run, and contains the result if it took less time to run. However I haven't been able to find any way to interrupt the evaluation of this function once it has been called.
For example:
// This is the unpredictable function
fn f() {
// Wait randomly for between 0 and 10 seconds
let mut rng = rand::thread_rng();
std::thread::sleep(std::time::Duration::from_secs(rng.gen_range(0, 10)));
}
fn main() {
for _ in 0..100 {
// Run f() here but so that the whole loop takes no more than 100 seconds
// by aborting f() if it takes longer than 1 second
}
}
I have found some methods that might work using futures with timeouts, but I would like to minimize overhead, and I am not sure how expensive it would be to create a future for every call to this function given that it will be called so many times.
Thanks