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

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