Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // ***********
- // header.h
- // ***********
- #include <vector>
- #include <future>
- #include <fstream>
- #include <sstream>
- #include <iostream>
- class Element {
- public:
- double val = 0;
- Element() : val(0) {}
- };
- class Container {
- public:
- std::vector<Element> elements;
- Container(int elemCount);
- };
- // ***********
- // source.cpp
- // ***********
- #include "header.h"
- Container::Container (int elemCount) {
- elements.resize(elemCount);
- }
- int process(int elemCount, int loopNum) {
- Container myContainer(elemCount);
- size_t cnt(0);
- auto t1 = std::chrono::high_resolution_clock::now();
- for (int i = 0; i < loopNum; ++i ) {
- for (auto& elem : myContainer.elements )
- ++elem.val;
- ++cnt;
- }
- auto t2 = std::chrono::high_resolution_clock::now();
- auto time_elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(t2-t1).count();
- std::cout << "loops: " << cnt << " ms: " << time_elapsed << std::endl; // this should be synchronized, of course
- return 0;
- }
- int main (int argc, char* argv[]) {
- int totalLoops(10000);
- int elemCount(300000);
- short threadsNum(4);
- // create threads
- int loopNum = totalLoops / threadsNum;
- std::vector<std::future<int>> futures;
- for ( int tIdx = 0; tIdx < threadsNum; ++tIdx )
- futures.push_back( std::async(std::launch::async, process, elemCount, loopNum) );
- // join
- for ( int tIdx = 0; tIdx < threadsNum; ++tIdx ) {
- if ( futures[tIdx].valid() ) {
- if ( futures[tIdx].get() != 0 )
- return -1;
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment