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