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

test_async_resumable.cpp 2.0KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  1. #include <chrono>
  2. #include <iostream>
  3. #include <string>
  4. #include "librf/librf.h"
  5. static std::mutex lock_console;
  6. template <typename T>
  7. void dump(size_t idx, std::string name, T start, T end, intptr_t count)
  8. {
  9. lock_console.lock();
  10. auto ns = std::chrono::duration_cast<std::chrono::nanoseconds>(end - start).count();
  11. std::cout << idx << ":" << name << " ";
  12. std::cout << count << " " << ns << " ns ";
  13. std::cout << (ns / count) << " ns/op" << " ";
  14. std::cout << (count * 100ll * 1000ll / ns) << "w/cps" << std::endl;
  15. lock_console.unlock();
  16. }
  17. static const intptr_t N = 3000000;
  18. //static const int N = 10;
  19. auto yield_switch(intptr_t coro) -> librf::generator_t<intptr_t>
  20. {
  21. for (intptr_t i = N / coro; i > 0; --i)
  22. co_yield i;
  23. co_return 0;
  24. }
  25. void resumable_switch(intptr_t coro, size_t idx)
  26. {
  27. librf::local_scheduler_t ls;
  28. auto start = std::chrono::steady_clock::now();
  29. for (intptr_t i = 0; i < coro; ++i)
  30. {
  31. go yield_switch(coro);
  32. }
  33. auto middle = std::chrono::steady_clock::now();
  34. dump(idx, "BenchmarkCreate_" + std::to_string(coro), start, middle, coro);
  35. librf::this_scheduler()->run_until_notask();
  36. auto end = std::chrono::steady_clock::now();
  37. dump(idx, "BenchmarkSwitch_" + std::to_string(coro), middle, end, N);
  38. }
  39. void resumable_main_resumable()
  40. {
  41. std::cout << __FUNCTION__ << std::endl;
  42. resumable_switch(1, 99);
  43. resumable_switch(1, 0);
  44. resumable_switch(10, 0);
  45. resumable_switch(100, 0);
  46. resumable_switch(1000, 0);
  47. resumable_switch(10000, 0);
  48. resumable_switch(30000, 0);
  49. /*
  50. std::thread works[32];
  51. for (size_t w = 1; w <= std::size(works); ++w)
  52. {
  53. for (size_t idx = 0; idx < w; ++idx)
  54. works[idx] = std::thread(&resumable_switch, 1000, idx);
  55. for (size_t idx = 0; idx < w; ++idx)
  56. works[idx].join();
  57. std::cout << std::endl << std::endl;
  58. }
  59. */
  60. }
  61. #if LIBRF_TUTORIAL_STAND_ALONE
  62. int main()
  63. {
  64. resumable_main_resumable();
  65. return 0;
  66. }
  67. #endif