超时后中止 Rust 中的评估

use*_*257 6 timeout rust

我有一个 Rust 函数(不是我写的),它要么以毫秒为单位返回,要么在失败前等待约 10 分钟。

我想将对这个函数的调用包装在一个函数中,如果运行时间超过 10 秒,则返回一个Optionwhich is None,如果运行时间较短,则包含结果。然而,我还没有找到任何方法来中断这个函数被调用后的评估。

例如:

// 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
    }
}
Run Code Online (Sandbox Code Playgroud)

我发现了一些可以使用带有超时的 future 的方法,但我想最大程度地减少开销,而且我不确定为该函数的每次调用创建一个 future 会花费多少成本,因为它会被调用很多次。

谢谢

Pet*_*all 4

异步执行的开销可能很小,特别是因为您的函数至少在几毫秒内运行,这已经非常慢了。

像这样的事情会起作用:

use rand::Rng;
use std::time::Duration;
use tokio::time::timeout;

async fn f() -> i32 {
    // Wait randomly for between 0 and 10 seconds
    let mut rng = rand::thread_rng();
    tokio::time::delay_for(Duration::from_secs(rng.gen_range(0, 10))).await;
    // return something
    1000
}

#[tokio::main]
async fn main() {
    for _ in 0..100 {
        if let Ok(result) = timeout(Duration::from_secs(1), f()).await {
            println!("result = {}", result);
        } else {
            // took too long
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

与性能一样,如果您担心某种特定方法可能会很慢,请测试该理论而不是假设您是对的。性能特征常常令人惊讶。