如何减轻过于频繁调用的功能?

我具有每秒调用5-6次,执行一些内部处理,然后将命令发送到外部系统的功能。外部系统不适合以此速率输入的handle命令。如何使函数仅每秒执行一次处理(或其他一些可配置的数量),而不管函数被调用的频率如何?

我尝试使用锁,但这只是导致随后的函数调用等待上一个函数完成。我觉得我想得太多了。

a665362 回答:如何减轻过于频繁调用的功能?

也许类似于下面的示例?请注意,在该程序中,MyFunction()每秒被调用多次(数千次),但每秒(一次)仅发送一次数据。

#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();
   }
}
本文链接:https://www.f2er.com/3070060.html

大家都在问