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