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

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. #include <chrono>
  2. #include <iostream>
  3. #include <string>
  4. #include <conio.h>
  5. #include "librf.h"
  6. static const intptr_t N = 10000000;
  7. //static const int N = 10;
  8. static std::mutex lock_console;
  9. template <typename T>
  10. void dump(size_t idx, std::string name, T start, T end)
  11. {
  12. lock_console.lock();
  13. auto ns = std::chrono::duration_cast<std::chrono::nanoseconds>(end - start).count();
  14. std::cout << idx << ":" << name << " ";
  15. std::cout << N << " " << ns << " ns ";
  16. std::cout << (ns / N) << " ns/op" << " ";
  17. std::cout << (N * 100 * 1000 / ns) << "w/cps" << std::endl;
  18. lock_console.unlock();
  19. }
  20. auto yield_switch(intptr_t coro)
  21. {
  22. for (intptr_t i = 0; i < N / coro; ++i)
  23. co_yield i;
  24. return N / coro;
  25. }
  26. void resumable_switch(intptr_t coro, size_t idx)
  27. {
  28. resumef::local_scheduler 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. go [=]
  34. {
  35. for (intptr_t i = 0; i < N / coro; ++i)
  36. co_yield i;
  37. return N / coro;
  38. };
  39. }
  40. resumef::this_scheduler()->run_until_notask();
  41. auto end = std::chrono::steady_clock::now();
  42. dump(idx, "BenchmarkSwitch_" + std::to_string(coro), start, end);
  43. }
  44. void resumable_main_resumable()
  45. {
  46. //resumable_switch(1, 0);
  47. //resumable_switch(10, 0);
  48. //resumable_switch(100, 0);
  49. //resumable_switch(10000, 0);
  50. //resumable_switch(10000000, 0);
  51. std::thread works[32];
  52. for (size_t w = 1; w <= _countof(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. }