基于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

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. #include <chrono>
  2. #include <iostream>
  3. #include <string>
  4. #include <thread>
  5. #include <deque>
  6. #include <mutex>
  7. #include "librf/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. #if defined(__GNUC__)
  23. static future_t<> passing_loop_all(channel_t<intptr_t> head, channel_t<intptr_t> tail)
  24. {
  25. for (int i = 0; i < LoopCount; ++i)
  26. {
  27. auto tstart = high_resolution_clock::now();
  28. co_await(head << 0);
  29. intptr_t value = co_await tail;
  30. auto dt = duration_cast<duration<double>>(high_resolution_clock::now() - tstart).count();
  31. std::cout << value << " cost time " << dt << "s" << std::endl;
  32. }
  33. }
  34. #endif
  35. void benchmark_main_channel_passing_next()
  36. {
  37. channel_t<intptr_t> head{1};
  38. channel_t<intptr_t> in = head;
  39. channel_t<intptr_t> tail{0};
  40. for (int i = 0; i < MaxNum; ++i)
  41. {
  42. tail = channel_t<intptr_t>{ 1 };
  43. go passing_next(in, tail);
  44. in = tail;
  45. }
  46. #if defined(__GNUC__)
  47. go passing_loop_all(head, tail);
  48. #else
  49. GO
  50. {
  51. for (int i = 0; i < LoopCount; ++i)
  52. {
  53. auto tstart = high_resolution_clock::now();
  54. co_await (head << 0);
  55. intptr_t value = co_await tail;
  56. auto dt = duration_cast<duration<double>>(high_resolution_clock::now() - tstart).count();
  57. std::cout << value << " cost time " << dt << "s" << std::endl;
  58. }
  59. };
  60. #endif
  61. this_scheduler()->run_until_notask();
  62. }
  63. #if LIBRF_TUTORIAL_STAND_ALONE
  64. int main()
  65. {
  66. benchmark_main_channel_passing_next();
  67. return 0;
  68. }
  69. #endif