Created
February 22, 2012 01:35
-
-
Save socantre/1880478 to your computer and use it in GitHub Desktop.
try out multiple threads
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 <climits> | |
#include <future> | |
#include <vector> | |
#include <thread> | |
#include <chrono> | |
#include <iostream> | |
#include <numeric> | |
#include <cassert> | |
struct busy_increment { | |
long long operator()(const volatile bool *b){ | |
long long i = 0; | |
for(;*b && i<LLONG_MAX;++i); | |
return i; | |
} | |
}; | |
struct add_future { | |
long long operator()(long long l,std::future<long long> &r) { | |
long long future_result = r.get(); | |
assert(future_result <= LLONG_MAX-l); | |
return l+future_result; | |
} | |
}; | |
int main() { | |
int max_thread_count = 32; | |
int seconds = 5; | |
for(int thread_count=1;thread_count<=max_thread_count;thread_count*=2) { | |
bool b = true; | |
std::vector<std::future<long long>> future; | |
for(int i=0;i<thread_count;++i) { | |
future.push_back(std::async(busy_increment(),&b)); | |
} | |
std::this_thread::sleep_for(std::chrono::seconds(seconds)); | |
b = false; | |
long long result = std::accumulate(begin(future),end(future),0LL,add_future()); | |
std::cout << thread_count << " threads\n"; | |
std::cout << "\tincrements per second performed: "; | |
std::cout << result/static_cast<float>(seconds) << '\n'; | |
std::cout << "\tincrements per second per thread: "; | |
std::cout << result/static_cast<float>(seconds)/thread_count << '\n'; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment