在结构体数组中搜索数值 C

huangapple go评论60阅读模式
英文:

Search a value in array of structures C

问题

如果我只是获取fault_code,如何在fault_table 中搜索这个值。谢谢。

英文:

I would like to know the fastest search method for array of structures

typedef struct fault_table_type {
    fault_types_t                    fault_code;         
    faultmanger_time_            process_time;      
    fault_behavior_enum_type_t       behavior;          
    FAILUREMGR_ACTION               fault_action;      
    bool                              forward_fault;    
    } fault_table_type_t;

static const fault_table_type_t fault_table[] = {
    
     {  COMMS_FAILURE,           60,         BEHAVIOR_3,   FAIL,    false,},  
     {   QUEUE_FAILURE,               10,         BEHAVIOR_1,      RESET,       true},

    };

If I am just getting the fault_code. How do I search this value in the fault_table. Thanks

答案1

得分: 1

线性搜索通过一个好老式的for循环。编译器可能会为您展开循环。如果没有,请编写一个宏来检查索引i并为您的两个记录调用它。您可以尝试lfind(),但由于函数调用开销,它可能会稍微慢一些。

下一步(如果您有1000个以上的记录)是对键进行排序,可以是数组本身或一个单独的索引,然后使用bsearch()。如果您从结构数组更改为数组的结构,则您的键已经排序并用作索引。

无论哪种情况,您首先从为可读性优化的代码开始。进行基准测试,然后查看是否需要进行更改。您还需要更精确地确定"最快"的含义是什么:最少的CPU周期、最少的缓存未命中、访问模式(冷热)、用户时间等。

英文:

Linear search via a good old for-loop. The compiler will probably unroll the loop that for you. If not write a macro to check index i and call it for your 2 records. You could try lfind() but it will probably be a little slower just due to function call overheads.

The next step (if you have 1000+ records) is to sort your key either the array itself array or a separate index then use bsearch(). If you change from an array of struct to a struct of arrays then your key is sorted and serves as an index.

In either case you start with code optimized for readability. Benchmark it and then see if you need to make changes. You also want to be more precise what you mean with fastest mean: fewest cpu cycles, fewest cache misses, what access pattern (cold vs hot), user time etc.

huangapple
  • 本文由 发表于 2023年2月14日 05:43:42
  • 转载请务必保留本文链接:https://go.coder-hub.com/75441472.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定