编译参数的时间处理

时间:2014-07-19 14:17:22

标签: c++ templates

我必须将两个数据通道中的一些数据分成两个队列。必须将从每个特定通道获取的数据写入其各自的队列。

因此我有一个功能:

void eatData(channel c, channel id)
{
   while (true)
   {
      if (channelid == 1)
      {
         write to queue 1;
      }
      else 
      {
         write to queue 2;
      }
   }
}

注意while循环 我正在轮询数据,应用程序非常非常时间敏感。 有没有办法摆脱那些if条件而不写下两个不同的函数:

void eatDataFromChannelOneAndWriteToQueueOne()
void eatDataFromChannelTwoAndWriteToQueueTwo()

可以使用模板来解决这个问题吗?

2 个答案:

答案 0 :(得分:2)

由于此代码时间敏感,我建议您使用std::vector个队列:

static std::vector<Queue_Type> data_container(MAXIMUM_CHANNELS);

void Collect_Data(const& Datum d,
                  unsigned int channel_number)
{
  data_container[channel_number].insert_value(d);
}

上面的代码使用std::vector构造函数来指定向量的初始元素数。使矢量动态调整大小是浪费时间。此外,固定的初始大小允许将矢量视为数组而无需调整大小。

对于循环队列,我建议使用2的幂的容量,以便您可以使用二进制AND运算而不是模数。我们做了这个改变,我们的性能大大提高,特别是因为我们的处理器没有任何除法或模数指令。

编辑1:
如果您的问题是从多个端口读取,那么您将分配固定在永久循环中:

void Read_Multiple_Ports(void)
{
  unsigned int channel_number = 0;
  while (true)
  {
    const Datum d = Read_Channel(channel_number);
    data_container[channel_number].insert_value(d);
    ++channel_number;

    // Use if statement rather than modulo
    // because modulo (division) may be more time
    // expensive than a jump.
    // If the number of channels is a power of 2,
    //    this could be replaced by an arithmetic AND
    //    to mask the value.
    if (channel_number >= MAXIMUM_CHANNELS)
    {
      channel_number = 0;
    }
  }
}

答案 1 :(得分:1)

我猜模板可以帮到你,例如:

template<int>
struct QueueSelector
{
    static YourQueue& Queue; 
};

template<int CH>
YourQueue& QueueSelector<CH>::Queue = queue2;

template<>
YourQueue& QueueSelector<1>::Queue = queue1;

template<int CH>
void eatData()
{
    processing with QueueSelector<CH>::Queue
}
相关问题