Skip to content

Instantly share code, notes, and snippets.

@reyoung
Created July 5, 2018 09:45
Show Gist options
  • Save reyoung/5578502e44a536e5502199cdec87536c to your computer and use it in GitHub Desktop.
Save reyoung/5578502e44a536e5502199cdec87536c to your computer and use it in GitHub Desktop.
BenchmarkThreadPool
#include "ThreadPool.h"
#include <chrono>
#include <iostream>
#include <thread>
#include <vector>
template <size_t HeavySize> class HeavyObject {
public:
HeavyObject() { vec_.resize(HeavySize); }
~HeavyObject() { vec_.clear(); }
private:
std::vector<char> vec_;
};
constexpr size_t ThreadNum = 6;
constexpr size_t IterPerThread = 1000;
constexpr size_t ByteSize = 64 * 1024 * 1024UL;
int main() {
{
auto cur = std::chrono::high_resolution_clock::now();
std::vector<std::thread> threads;
for (size_t i = 0; i < ThreadNum; ++i) {
threads.emplace_back([] {
for (size_t j = 0; j < IterPerThread; ++j) {
HeavyObject<ByteSize> obj;
}
});
}
for (auto &th : threads) {
th.join();
}
std::cout << "Plain Thread "
<< (std::chrono::high_resolution_clock::now() - cur).count() /
1000.0 / 1000.0 / 1000.0
<< " sec" << std::endl;
}
{
auto cur = std::chrono::high_resolution_clock::now();
ThreadPool pool(ThreadNum);
for (size_t i=0;i<ThreadNum * IterPerThread; ++i) {
if (i + 1 == ThreadNum * IterPerThread) {
auto future = pool.enqueue([] {
HeavyObject<ByteSize> obj;
});
future.wait(); // wait the final job
} else {
pool.enqueue([] {
HeavyObject<ByteSize> obj;
});
}
}
std::cout << "Thread Pool "
<< (std::chrono::high_resolution_clock::now() - cur).count() /
1000.0 / 1000.0 / 1000.0
<< " sec" << std::endl;
}
return 0;
}
/home/reyoung/Projects/ThreadPool/cmake-build-release/ThreadPoolBenchmark
Plain Thread 31.7059 sec
Thread Pool 31.7196 sec
Process finished with exit code 0
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment