fork(1) download
  1. /*
  2.  
  3. ロックなし
  4. loop start
  5. 180ms
  6. loop start
  7. 116ms
  8. loop start
  9. 120ms
  10. loop start
  11. 138ms
  12. loop start
  13. 133ms
  14. ロックあり
  15. loop start
  16. 77ms
  17. loop start
  18. 85ms
  19. loop start
  20. 75ms
  21. loop start
  22. 80ms
  23. loop start
  24. 98ms
  25.  
  26. */
  27. #include <iostream>
  28. #include <ppl.h>
  29. #include <mutex>
  30. #include <vector>
  31. #include <string>
  32. #include <chrono>
  33. #include <memory>
  34. using namespace std;
  35.  
  36. auto f_nolock()
  37. {
  38. constexpr auto n = 1000 * 1000;
  39.  
  40. vector<string> v;
  41. v.reserve(n);
  42. for ( auto i = 0; i < n; i++ )
  43. {
  44. v.push_back( string( static_cast<string::size_type>(100), 'B') );
  45. }
  46.  
  47. vector<size_t> index_found;
  48. cout << "loop start" << endl;
  49.  
  50. auto ts = std::chrono::system_clock::now();
  51. vector<vector<size_t>> partial_results;
  52. partial_results.resize(v.size());
  53. Concurrency::parallel_for(size_t{}, v.size(),
  54. [&](size_t i)
  55. {
  56. if ( v[i].find("AAA") != string::npos )
  57. {
  58. partial_results[i].push_back(i);
  59. }
  60. }
  61. );
  62. vector<size_t> results;
  63. for ( auto &a : partial_results )
  64. results.insert(results.end(), a.begin(), a.end());
  65. auto te = std::chrono::system_clock::now();
  66. cout << std::chrono::duration_cast<std::chrono::milliseconds>(te - ts).count() << "ms" << endl;
  67.  
  68. for ( auto & elem : index_found )
  69. {
  70. cout << elem;
  71. }
  72. }
  73.  
  74.  
  75. auto f_lock()
  76. {
  77. constexpr auto n = 1000 * 1000;
  78.  
  79. vector<string> v;
  80. v.reserve(n);
  81. for ( auto i = 0; i < n; i++ )
  82. {
  83. v.push_back(string(static_cast<string::size_type>(100), 'B'));
  84. }
  85.  
  86. vector<size_t> index_found;
  87. cout << "loop start" << endl;
  88.  
  89. auto ts = std::chrono::system_clock::now();
  90. mutex m;
  91. Concurrency::parallel_for(size_t{}, v.size(),
  92. [&](size_t i)
  93. {
  94. if ( v[i].find("AAA") != string::npos )
  95. {
  96. lock_guard<mutex> lock1{ m };
  97. index_found.push_back(i);
  98. }
  99. }
  100. );
  101. auto te = std::chrono::system_clock::now();
  102. cout << std::chrono::duration_cast<std::chrono::milliseconds>(te - ts).count() << "ms" << endl;
  103.  
  104. for ( auto & elem : index_found )
  105. {
  106. cout << elem;
  107. }
  108. }
  109.  
  110.  
  111. int main()
  112. {
  113. cout << "ロックなし" << endl;
  114. for ( auto i = 0; i < 5; i++ )
  115. f_nolock();
  116.  
  117. cout << "ロックあり" << endl;
  118. for ( auto i = 0; i < 5; i++ )
  119. f_lock();
  120. }
  121.  
Compilation error #stdin compilation error #stdout 0s 0KB
stdin
Standard input is empty
compilation info
prog.cpp:28:17: fatal error: ppl.h: No such file or directory
 #include <ppl.h>
                 ^
compilation terminated.
stdout
Standard output is empty