假设我正确地理解了这个问题,我的方法是使用模运算,将每个脉冲序列描述为布尔函数,并将时间戳作为函数的参数,例如:
// Returns true iff the pulse is present at the specified time
bool IsPulseActiveAtTime(long int theTime);
这样做的好处是,你可以模拟一个无限系列的脉冲,而只使用一个小的,固定的内存量。如果您需要的话,它还允许您高效地查询每个脉冲序列在过去/将来的任何时间(即不仅仅是当前时间)的预期状态。
下面是一个简单的演示程序,它在100个模拟“秒”的过程中打印出一个包含4个脉冲的股票行情磁带:
#include <stdio.h>
class PulseSequence
{
public:
PulseSequence(long int startTime, long int duration, long int interval)
: _startTime(startTime)
, _duration(duration)
, _interval(interval)
{
// empty
}
bool IsPulseActiveAtTime(long int theTime) const
{
if (theTime < _startTime) return false;
return ((theTime-_startTime) % _interval) < _duration;
}
private:
const long int _startTime; // time at which the first pulse starts
const long int _duration; // length of each pulse
const long int _interval; // difference between the start-time of one pulse and the start-time of the next
};
// Unit test/example
int main(int, char **)
{
const int NUM_PULSE_SEQUENCES = 4;
const PulseSequence sequences[NUM_PULSE_SEQUENCES] = {
PulseSequence(0, 3, 5),
PulseSequence(1, 2, 6),
PulseSequence(3, 3, 4),
PulseSequence(5, 1, 3),
};
for (long int curTime = 0; curTime < 100; curTime++)
{
printf("curTime=%02li: [", curTime);
for (int i=0; i<NUM_PULSE_SEQUENCES; i++) putchar(sequences[i].IsPulseActiveAtTime(curTime)?('0'+i):' ');
printf("]\n");
}
return 0;
}
$ ./a.out
curTime=00: [0 ]
curTime=01: [01 ]
curTime=02: [01 ]
curTime=03: [ 2 ]
curTime=04: [ 2 ]
curTime=05: [0 23]
curTime=06: [0 ]
curTime=07: [012 ]
curTime=08: [ 123]
curTime=09: [ 2 ]
curTime=10: [0 ]
curTime=11: [0 23]
curTime=12: [0 2 ]
curTime=13: [ 12 ]
[...]