I am working on a C++ project where in I need to compute average of std::deque data. This is what I have written so far
std::deque<float> list1(200,0);
std::deque<float> list2;
pthread_mutex_t mut;
/*thread1 populates list2 say every 50 milliseconds*/
while(true)
{
float f;
... //some operation
pthread_mutex_lock(&mut);
list2.push_back(f);
if(list2.size()==201)
list2.pop_front();
pthread_mutex_unlock(&mut);
}
/*thread2 copies list2 data into list1 every 1 second*/
while(true)
{
pthread_mutex_lock(&mut);
if(list2.size()==200)
std::copy(list2.begin(),list2.end(),std::back_inserter(list1.begin()));
pthread_mutex_unlock(&mut);
if(list1.size()==200)
{
float sum=std::accumulate(list1.begin(),list1.end(),0.0f);
float avg=sum/list1.size();
}
}
As you can see every 1 sec I am copying the same old data (except last 20 elements) into list1 which I feel not optimal. So is there a way to optimise this code so that I copy only the newly added elements of list2 into list1 at the end.