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

C++协程中是否存在比std::suspend_always更高效的等待器?

C++协程优化二分查找:std::suspend_always性能瓶颈的优化方案

我在1GB的唯一随机整数有序数组上尝试用C++协程优化二分查找工作负载,以此触发多次内存缺失。当访问arr[mid]导致内存缺失时,我会使用co_await,随后利用另一个带循环缓冲区的协程发起额外请求,以重叠内存缺失。但std::suspend_always似乎成为性能瓶颈,想了解是否有更高效的处理方式。

struct BSCoroutineHandler {
  struct promise_type {
    int value;
    BSCoroutineHandler get_return_object() {
      return {.h_ = std::coroutine_handle<promise_type>::from_promise(*this)};
    }
    std::suspend_never initial_suspend() { return {}; }
    std::suspend_always final_suspend() noexcept { return {}; }
    void return_value(int v) { value = v; }
    void unhandled_exception() { std::terminate(); }
  };

  std::coroutine_handle<promise_type> h_;

  int get() { return h_.promise().value; }
  void resume() { this->h_.resume(); }
  bool done() { return this->h_.done(); }
};

BSCoroutineHandler binarySearchCoroutine(int *arr, int target,
                                         const int arr_size) {
  int low = 0, high = arr_size - 1;

  while (low <= high) {
    int mid = low + (high - low) / 2;
    __builtin_prefetch(&arr[mid]);
    co_await std::suspend_always{};
    if (arr[mid] == target) {
      co_return mid;
    } else if (arr[mid] < target) {
      low = mid + 1;
    } else {
      high = mid - 1;
    }
  }

  co_return -1; // Not found
}

性能分析图

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.16 02:05:07