假设我每毫秒都有输入数据。 5 秒后我想输出最后 5 秒时间窗口的最大值和最小值。
比较频繁的整数输入数据的最快方法是什么?我举了一个很简单的例子。通常使用这样的东西不好吗?有没有更快的方法但不使用数组进行缓冲?
myMainFuntion() {
int static currentMIN = 30000; // Just initialize to a value that will never be output by getSensorData
int static currentMAX = 0;
int static acquisition_counter = 0;
a = getSensorData() // called each 1 ms
if (a > currentMAX) {
currentMAX = a;
}
if (a < currentMIN) {
currentMIN = a;
}
acquisition_counter++;
if (acquisition_counter == 5000) {
output(MAX);
output(MIN);
}
}
最佳答案
看起来还可以,除了一些细节之外,您的功能没有太多需要优化的地方:
- 返回类型应该是
void
而不是省略。 a
未定义。- 您应该输出
currentMIN
和currentMAX
而不是MIN
和MAX
。 - 您应该在输出后重置最小和最大变量的值。
- 在类型前面加上
static
关键字更符合习惯。
修改后的代码:
void myMainFuntion(void) {
static int currentMIN = 30000; // Just initialize to a value that will never be output by getSensorData
static int currentMAX = 0;
static int acquisition_counter = 0;
int a;
a = getSensorData() // called every 1 ms
if (a > currentMAX) {
currentMAX = a;
}
if (a < currentMIN) {
currentMIN = a;
}
acquisition_counter++;
if (acquisition_counter == 5000) {
output(currentMAX);
output(currentMIN);
currentMAX = 0;
currentMIN = 30000;
acquisition_counter = 0;
}
}
关于c - 比较频繁输入数据和存储 MAX 和 MIN 值的快速方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53307859/