超时后中止 Rust 中的评估 [英] Aborting evaluation in Rust after a timeout

查看:25
本文介绍了超时后中止 Rust 中的评估的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have a function in Rust (that I did not write) which either returns in milliseconds or grinds for ~10 minutes before failing.

我想把对这个函数的调用包装在返回一个 Option 的东西中,如果运行时间超过 10 秒,它是 None,并且包含结果,如果运行时间更短.但是,一旦调用此函数,我就无法找到任何方法来中断它的评估.

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.

例如:

// 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.

谢谢

推荐答案

异步执行的开销可能很小,尤其是因为您的函数至少在几毫秒内运行,这已经很慢了.

The overhead of asynchronous execution is likely to be minimal, especially since your function runs in at least milliseconds, which is already very slow.

这样的事情会起作用:

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
        }
    }
}

<小时>

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


As ever with performance, if you are concerned that one particular approach could be slow, test the theory rather than assuming you're right. Performance characteristics can often be surprising.

这篇关于超时后中止 Rust 中的评估的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆