c - 比较频繁输入数据和存储 MAX 和 MIN 值的快速方法

标签 c performance embedded

假设我每毫秒都有输入数据。 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 未定义。
  • 您应该输出 currentMINcurrentMAX 而不是 MINMAX
  • 您应该在输出后重置最小和最大变量的值。
  • 在类型前面加上 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/

相关文章:

c - main 的多个定义 --> 如何只添加另一个标题中的一些函数?

javascript - 加速多个 async/await 调用的执行

c - ATSAM4s8b,如何等待 USB 设备连接

c - TRF7970 : Mifare Classic authentication

performance - 2D FFT中的3D FFT分解

linux - 一个项目中的不同版本的 yocto

c++ - 将现有的 HBITMAP 重置为桌面背景 (Win32)

c - 尝试将数据从一个结构复制到另一个结构时出现段错误

c++ - Memcpy 字符指针

javascript - 如何提高js中Date对象到字符串的加载时间?