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

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