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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  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. 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(30000, 0);
  54. /*
  55. std::thread works[32];
  56. for (size_t w = 1; w <= _countof(works); ++w)
  57. {
  58. for (size_t idx = 0; idx < w; ++idx)
  59. works[idx] = std::thread(&resumable_switch, 1000, idx);
  60. for (size_t idx = 0; idx < w; ++idx)
  61. works[idx].join();
  62. std::cout << std::endl << std::endl;
  63. }
  64. */
  65. }