0

I have this function that gets called 5-6 times per second, performs some internal processing, and then sends a command to an external system. The external system isn't fit the handle commands coming in at this rate. How can I make it so that the function only goes through its processing once a second (or some other configurable amount) regardless of how often the function is called?

I tried using a lock, but that just resulted in subsequent function calls waiting for the previous one to finish. I feel like I'm overthinking this.

  • 1
    The obvious solution is to change the callers so they call your function only once per second. Otherwise, you have to decide what your function will do if called more than once per second. Do you want it wait 1 second before proceeding? Do you want to do the internal processing but skip sending the command? Do you want to ignore the extra calls? – Raymond Chen Nov 19 '19 at 21:54

1 Answers1

2

Perhaps something like the example below? Note that in this program MyFunction() is being called many (thousands?) of times per second, but it only (pretends to) send data once a second.

#include <chrono>
#include <iostream>

typedef std::chrono::steady_clock::time_point my_time_point_type;

void MyFunction()
{
   static my_time_point_type previousSendTime;

   const my_time_point_type now = std::chrono::steady_clock::now();

   const long long nanosSinceLastSend = (now-previousSendTime).count();
   if (nanosSinceLastSend > 1*1000000000LL)
   {
      std::cout << "SEND DATA NOW!" << std::endl;
      previousSendTime = now;
   }
}

int main(int argv, char ** argc)
{
   while(1)
   {
      MyFunction();
   }
}
Jeremy Friesner
  • 70,199
  • 15
  • 131
  • 234