Quickly find whether a value is present in a C array?

前端 未结 15 1278
灰色年华
灰色年华 2021-01-29 17:30

I have an embedded application with a time-critical ISR that needs to iterate through an array of size 256 (preferably 1024, but 256 is the minimum) and check if a value matches

15条回答
  •  温柔的废话
    2021-01-29 18:01

    Assuming your processor runs at 204 MHz which seems to be the maximum for the LPC4357, and also assuming your timing result reflects the average case (half of the array traversed), we get:

    • CPU frequency: 204 MHz
    • Cycle period: 4.9 ns
    • Duration in cycles: 12.5 µs / 4.9 ns = 2551 cycles
    • Cycles per iteration: 2551 / 128 = 19.9

    So, your search loop spends around 20 cycles per iteration. That doesn't sound awful, but I guess that in order to make it faster you need to look at the assembly.

    I would recommend dropping the index and using a pointer comparison instead, and making all the pointers const.

    bool arrayContains(const uint32_t *array, size_t length)
    {
      const uint32_t * const end = array + length;
      while(array != end)
      {
        if(*array++ == 0x1234ABCD)
          return true;
      }
      return false;
    }
    

    That's at least worth testing.

提交回复
热议问题