基于C++ Coroutines提案 ‘Stackless Resumable Functions’编写的协程库
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

benchmark_channel_passing_next.cpp 1.7KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. #include <chrono>
  2. #include <iostream>
  3. #include <string>
  4. #include <thread>
  5. #include <deque>
  6. #include <mutex>
  7. #include "librf.h"
  8. using namespace librf;
  9. using namespace std::chrono;
  10. using namespace std::literals;
  11. const static auto MaxNum = 100000;
  12. const static auto LoopCount = 100;
  13. using int_channel_ptr = std::shared_ptr<channel_t<intptr_t>>;
  14. static future_t<> passing_next(channel_t<intptr_t> rd, channel_t<intptr_t> wr)
  15. {
  16. for (int i = 0; i < LoopCount; ++i)
  17. {
  18. intptr_t value = co_await rd;
  19. co_await wr.write(value + 1);
  20. }
  21. }
  22. static future_t<> passing_loop_all(channel_t<intptr_t> head, channel_t<intptr_t> tail)
  23. {
  24. for (int i = 0; i < LoopCount; ++i)
  25. {
  26. auto tstart = high_resolution_clock::now();
  27. co_await(head << 0);
  28. intptr_t value = co_await tail;
  29. auto dt = duration_cast<duration<double>>(high_resolution_clock::now() - tstart).count();
  30. std::cout << value << " cost time " << dt << "s" << std::endl;
  31. }
  32. }
  33. void benchmark_main_channel_passing_next()
  34. {
  35. channel_t<intptr_t> head{1};
  36. channel_t<intptr_t> in = head;
  37. channel_t<intptr_t> tail{0};
  38. for (int i = 0; i < MaxNum; ++i)
  39. {
  40. tail = channel_t<intptr_t>{ 1 };
  41. go passing_next(in, tail);
  42. in = tail;
  43. }
  44. #if defined(__GNUC__)
  45. go passing_loop_all(head, tail);
  46. #else
  47. GO
  48. {
  49. for (int i = 0; i < LoopCount; ++i)
  50. {
  51. auto tstart = high_resolution_clock::now();
  52. co_await (head << 0);
  53. intptr_t value = co_await tail;
  54. auto dt = duration_cast<duration<double>>(high_resolution_clock::now() - tstart).count();
  55. std::cout << value << " cost time " << dt << "s" << std::endl;
  56. }
  57. };
  58. #endif
  59. this_scheduler()->run_until_notask();
  60. }
  61. int main()
  62. {
  63. benchmark_main_channel_passing_next();
  64. return 0;
  65. }