C 比较频繁输入数据并存储最大值和最小值的快速方法
假设我每毫秒输入一次数据。 5秒后,我想输出最后5秒时间窗口的最大值和最小值 比较频繁整数输入数据的最快方法是什么?我举了一个非常简单的例子。一般来说,使用这样的东西不好吗?有没有一种更快但不使用数组进行缓冲的方法C 比较频繁输入数据并存储最大值和最小值的快速方法,c,performance,embedded,C,Performance,Embedded,假设我每毫秒输入一次数据。 5秒后,我想输出最后5秒时间窗口的最大值和最小值 比较频繁整数输入数据的最快方法是什么?我举了一个非常简单的例子。一般来说,使用这样的东西不好吗?有没有一种更快但不使用数组进行缓冲的方法 myMainFuntion() { int static currentMIN = 30000; // Just initialize to a value that will never be output by getSensorData int static c
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;
}
}
看起来还可以,除了一些细节外,您的函数中没有太多需要优化的地方: 返回类型应为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;
}
}
现在还不完全清楚你在问什么-1ms与一些比较操作相比非常慢。你的cpu有多慢?如果你愿意滚动浏览Geeksforgeks和leetcode垃圾,在你最喜欢的搜索引擎中搜索滑动窗口最大值可能会有帮助。5秒钟后,接下来会发生什么?就这样结束了吗?如果目标是最后5秒的持续最小/最大值,则应考虑其他方法。最小值/最大值是否重置,或者应在5.0s后每毫秒输出一次最小值/最大值?否则,我们这里只有5000个样本的最小/最大值。尽管我会用currentMIN=INT_max初始化,但JohnDoe有一个很好的解决方案;currentMAX=INT_MIN;避免使用神奇的数字。你问的问题还不完全清楚-1ms与一些比较操作相比非常慢。你的cpu有多慢?如果你愿意滚动浏览Geeksforgeks和leetcode垃圾,在你最喜欢的搜索引擎中搜索滑动窗口最大值可能会有所帮助。5秒钟后,接下来会发生什么?就这样结束了吗?如果目标是最后5秒的持续最小/最大值,则应考虑其他方法。最小值/最大值是否重置,或者应在5.0s后每毫秒输出一次最小值/最大值?否则,我们这里只有5000个样本的最小/最大值。尽管我会用currentMIN=INT_max初始化,但JohnDoe有一个很好的解决方案;currentMAX=INT_MIN;避免使用幻数。没错,如果第一个样本是最小值,其他所有样本都较大,我的建议就会失败。删除。@chqrlie-关于输出后最小值和最大值的重置。这将取决于特定的用例。可能需要,也可能不需要。在任何情况下,都需要采集计数器的其余部分。如果第一个样本是最小值,而所有其他样本都较大,则我的建议将失败。删除。@chqrlie-关于输出后最小值和最大值的重置。这将取决于特定的用例。可能需要,也可能不需要。在任何情况下,都需要采集计数器的其余部分