벡터 벡터의 모든 요소를 검사하기 위해 다음과 같은 병렬 코드를 작성했습니다. 주어진 조건을 만족하는 vector<vector<int> >
의 요소 만 저장합니다. 그러나, 내 문제는 vector<vector<int> >
내의 벡터 중 일부가 꽤 큰 반면 다른 것들은 꽤 작습니다. 이로 인해 내 코드가 thread.join()을 수행하는 데 오랜 시간이 걸립니다. 누군가 제 코드의 성능을 어떻게 향상시킬 수 있는지 제안 해주십시오.스레드 결합의 성능 문제
void check_if_condition(vector<int>& a, vector<int>& satisfyingElements)
{
for(vector<int>::iterator i1=a.begin(), l1=a.end(); i1!=l1; ++i1)
if(some_check_condition(*i1))
satisfyingElements.push_back(*i1);
}
void doWork(std::vector<vector<int> >& myVec, std::vector<vector<int> >& results, size_t current, size_t end)
{
end = std::min(end, myVec.size());
int numPassed = 0;
for(; current < end; ++current) {
vector<int> satisfyingElements;
check_if_condition(myVec[current], satisfyingElements);
if(!satisfyingElements.empty()){
results[current] = satisfyingElements;
}
}
}
int main()
{
std::vector<std::vector<int> > myVec(1000000);
std::vector<std::vector<int> > results(myVec.size());
unsigned numparallelThreads = std::thread::hardware_concurrency();
std::vector<std::thread> parallelThreads;
auto blockSize = myVec.size()/numparallelThreads;
for(size_t i = 0; i < numparallelThreads - 1; ++i) {
parallelThreads.emplace_back(doWork, std::ref(myVec), std::ref(results), i * blockSize, (i+1) * blockSize);
}
//also do work in this thread
doWork(myVec, results, (numparallelThreads-1) * blockSize, myVec.size());
for(auto& thread : parallelThreads)
thread.join();
std::vector<int> storage;
storage.reserve(numPassed.load());
auto itRes = results.begin();
auto itmyVec = myVec.begin();
auto endRes = results.end();
for(; itRes != endRes; ++itRes, ++itmyVec) {
if(!(*itRes).empty())
storage.insert(storage.begin(),(*itRes).begin(), (*itRes).end());
}
std::cout << "Done" << std::endl;
}
더 읽기 쉬운'itres-> begin()'을 말하지 않는 이유는 무엇입니까? 그리고 'empty'는 함수 호출이어야합니다. –
이유는 없지만 (itRes-> begin()) 및 if (! (* itRes) .empty()) 같은 효과가있는 경우에는 마찬가지입니다. –
분명히 다른 함수를 호출하기 때문에. –