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

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