You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Rust动态调用可变参随机函数的异步问题与性能优化咨询

Rust异步随机端点选择的问题与性能优化

编译错误问题

我有一组带可变参数的异步函数,希望运行时随机选择其一循环调用,为此编写了choose_random_endpoint函数:

pub async fn choose_random_endpoint(
    &self,
    rng: ThreadRng,
    endpoint_type: EndpointType,
) -> impl Future<Output = Result<std::string::String, MyError>> {
    match endpoint_type {
        EndpointType::Type1 => {
            let endpoint_arguments = self.choose_endpoint_arguments(rng);
            let endpoint = endpoint1(&self.arg1, &self.arg2, &endpoint_arguments.arg3);
            endpoint
        }
        EndpointType::Type2 => {
            let endpoint_arguments = self.choose_endpoint_arguments(rng);
            let endpoint = endpoint2(
                &self.arg1,
                &self.arg2,
                &endpoint_arguments.arg3,
                rng.clone(),
            );
            endpoint
        }
        EndpointType::Type3 => {
            let endpoint_arguments = self.choose_endpoint_arguments(rng);
            let endpoint = endpoint3(
                &self.arg1,
                &self.arg2,
                &endpoint_arguments.arg3,
                rng.clone(),
            );
            endpoint
        }
    }
}

但编译时出现如下错误:

expected opaque type `impl Future<Output = Result<std::string::String, MyError>>` (opaque type at <src/calls/type1.rs:14:6>)
   found opaque type `impl Future<Output = Result<std::string::String, MyError>>` (opaque type at <src/type2.rs:19:6>)

编译器提示使用await可解决该问题,但我担心此操作会带来性能开销。

定时调用与主线程阻塞问题

外层调用函数如下(假设存在循环调用该函数的逻辑):

pub async fn make_call(arg1: &str, arg2: &str) -> Result<String> {
    let mut rng = rand::thread_rng();
    let random_endpoint_type = choose_random_endpoint_type(&mut rng);
    let random_endpoint = choose_random_endpoint(&rng, random_endpoint_type);
    // call the endpoint
    Ok(response)
}

现在我希望每X秒调用一次make_call,且不希望主线程在调用耗时较长的端点时被阻塞,请问是否需要每X秒新建一个线程来调用make_call?

ThreadRng克隆的性能优化问题

从性能角度看,多次克隆ThreadRng的开销较大,是否存在更高效的实现方式?


内容的提问来源于stack exchange,提问作者raf

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.03 00:05:20