Darkriser

Multi-threading performance

Nov 16th, 2015
284
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.63 KB | None | 0 0
  1. // ***********
  2. // header.h
  3. // ***********
  4.  
  5. #include <vector>
  6. #include <future>
  7. #include <fstream>
  8. #include <sstream>
  9. #include <iostream>
  10.  
  11. class  Element {
  12. public:
  13.     double val = 0;
  14.     Element() : val(0) {}
  15. };
  16.  
  17. class Container {
  18. public:
  19.     std::vector<Element> elements;
  20.     Container(int elemCount);
  21. };
  22.  
  23.  
  24. // ***********
  25. // source.cpp
  26. // ***********
  27.  
  28. #include "header.h"
  29.  
  30. Container::Container (int elemCount) {
  31.     elements.resize(elemCount);
  32. }
  33.  
  34. int process(int elemCount, int loopNum) {
  35.    
  36.     Container myContainer(elemCount);
  37.     size_t cnt(0);
  38.    
  39.     auto t1 = std::chrono::high_resolution_clock::now();
  40.     for (int i = 0; i < loopNum; ++i ) {
  41.         for (auto& elem : myContainer.elements )
  42.         ++elem.val;
  43.         ++cnt;
  44.     }
  45.  
  46.     auto t2 = std::chrono::high_resolution_clock::now();
  47.     auto time_elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(t2-t1).count();
  48.     std::cout << "loops: " << cnt << " ms: " << time_elapsed << std::endl; // this should be synchronized, of course
  49.  
  50.     return 0;
  51. }
  52.  
  53. int main (int argc, char* argv[]) {
  54.  
  55.     int totalLoops(10000);
  56.     int elemCount(300000);
  57.     short threadsNum(4);
  58.        
  59.     // create threads
  60.     int loopNum = totalLoops / threadsNum;
  61.     std::vector<std::future<int>> futures;
  62.     for ( int tIdx = 0; tIdx < threadsNum; ++tIdx )
  63.         futures.push_back( std::async(std::launch::async, process, elemCount, loopNum) );
  64.     // join
  65.     for ( int tIdx = 0; tIdx < threadsNum; ++tIdx ) {
  66.         if ( futures[tIdx].valid() ) {
  67.             if ( futures[tIdx].get() != 0 )
  68.                 return -1;
  69.         }
  70.     }
  71. }
Advertisement
Add Comment
Please, Sign In to add comment