Created
August 28, 2019 04:55
-
-
Save madoodia/b40f2e9e696b480851ce0650988bccc9 to your computer and use it in GitHub Desktop.
Sample of threading test
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <iostream> | |
#include <thread> | |
#include <chrono> | |
#include <algorithm> | |
#include <vector> | |
#include <cassert> | |
void thFunc(int start, int end) | |
{ | |
for (int i = start; | |
i < end; | |
i++) | |
{ | |
std::cout << "Hi from thread " << i << std::endl; | |
} | |
} | |
int main() | |
{ | |
auto start = std::chrono::steady_clock::now(); | |
std::vector<std::thread> workers; | |
char threadCount = 8; | |
int all = 10000; | |
int each = all / threadCount; | |
for (int i = 0; | |
i < threadCount; | |
i++) | |
{ | |
int thisTime = 0; | |
if ((all - (i + 1)*each) < each) | |
thisTime = ((i + 1)*each) + (all - (i + 1)*each); | |
else | |
thisTime = (i + 1)*each; | |
//std::cout << "\nstart: " << i * each << '\n'; | |
//std::cout << "\nend: " << thisTime << '\n'; | |
std::thread th(&thFunc, i * each, thisTime); | |
workers.push_back(std::move(th)); | |
assert(!th.joinable()); | |
} | |
//std::cout << "Hi from main!\n" << std::endl; | |
std::for_each(workers.begin(), workers.end(), [](std::thread &th) | |
{ | |
assert(th.joinable()); | |
th.join(); | |
}); | |
auto finish = std::chrono::steady_clock::now(); | |
double elapsed_seconds = std::chrono::duration_cast<std::chrono::duration<double>>(finish - start).count(); | |
std::cout << "\nTime: " << elapsed_seconds << '\n'; | |
std::cin.get(); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment