0

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.

moooeeeep
  • 31,622
  • 22
  • 98
  • 187
Harry
  • 2,177
  • 1
  • 19
  • 33
  • Unrelated to your problem, but why don't you use `std::thread`? – Jodocus Dec 12 '17 at 14:39
  • ... and `std::condition_variable` ? – moooeeeep Dec 12 '17 at 14:40
  • my compiler doesn't support c++11 standard – Harry Dec 12 '17 at 14:41
  • So, everytime a change occurs, you want to compute the average value for the most recent 200 items? – moooeeeep Dec 12 '17 at 15:20
  • yes...I am unnecessarily copying first 180 elements which are already present in the list(of course not in the required position but from position 20 onwards) – Harry Dec 12 '17 at 15:24
  • Normally you'd have a ringbuffer with a separate read and write position instead of a linked list. You can easily copy ranges then. Have you thought about that? Otherwise you'd need to keep track of the count of newly added items since the last copy as well, I guess. (Or allow to remove items from the queue as you copy them.) – moooeeeep Dec 12 '17 at 15:32
  • to be honest, the cost of copying 200 floats is probably insignificant compared to the cost of the mutex locks. – Richard Hodges Dec 12 '17 at 16:05

1 Answers1

0

You could simply clear list2 every time you copy its contents.

amc176
  • 1,514
  • 8
  • 19
  • I cannot clear list2 completely. I need to only add the new element to the list and pop out the oldest element which is obviously present at the front, and I am doing pop_front operation once list2 size reaches 201. – Harry Dec 12 '17 at 14:41