What i like to do is simple benchmark using CTPL or any other thread library.
I created simple app for benchmark:
#include <iostream>
#include <string>
#include <thread>
#include <vector>
#include <algorithm>
#include <random>
#include <chrono>
#include <ctime>
#include "ctpl_stl.h"
class Item
{
public:
Item() {
//std::cout << "Item ctr" << std::endl;
workToDo = 0;
}
virtual ~Item() {
//std::cout << "Item dcr" << std::endl;
}
void Work() {
std::cout << "Item work:" << time << std::endl;
std::this_thread::sleep_for(std::chrono::milliseconds(workToDo));
}
void SetWork(int workTime) { workToDo = workTime; }
private:
int workToDo;
};
int randomFrom(int min, int max) { return min + (int)((double)rand() / (RAND_MAX+1) * (max-min+1)); }
void workFunction(int id, Item *t) {
t->Work();
}
int main()
{
ctpl::thread_pool pool(std::thread::hardware_concurrency());
// How many items
uint32_t itemsCount = 100;
// How many % of working items will be (rest of them will do nothing)
uint8_t itemsPrecent = 10;
// Make a list of items
std::vector<Item*> itemList;
for(uint32_t i = 0 ; i < itemsCount ; i++)
itemList.push_back(new Item);
// Calculate how many items will work (from percentage)
uint32_t workingItems = (itemsCount * itemsPrecent)/100;
std::srand(unsigned(std::time(0)));
// Make random 'sleep' for each working item
for(uint32_t i = 0 ; i < workingItems ; i++)
itemList[i]->SetWork(randomFrom(200, 5000));
// Randomize list
std::random_shuffle(itemList.begin(), itemList.end());
// Make work for all items
for(uint32_t i = 0 ; i < itemsCount ; i++)
{
Item *itemOnList = itemList[i];
pool.push(workFunction, itemOnList);
}
int i = 0 ;
// Clean up
for (Item *i : itemList ) {
delete i;
}
return 0;
}
But is not working as i like to expect ... is not doing anything 'heavy' here :/
Wh i like to do is create XX of objects, then some of them (~10%) will have some calculations (here is just sleep), to 'empty list' i need go over list make 'function on all objects'.
I was think that CTPL will be good solution for it, as i don't need re-invent wheel with thread pool.
If any one have better libraries (preferred header only), to make calculation in parallels will be great :)
Aucun commentaire:
Enregistrer un commentaire