C++ Optimize if/else condition

后端 未结 5 677
耶瑟儿~
耶瑟儿~ 2021-02-07 05:02

I have a single line of code, that consumes 25% - 30% of the runtime of my application. It is a less-than comparator for an std::set (the set is implemented with a Red-Black-Tre

5条回答
  •  梦如初夏
    2021-02-07 05:44

    An easy solution is precompute a sort-identifier comprised of the cost as most significant and the id as the rest.

    E.g.,

    struct Entry
    {
        double cost_;
        long id_;
        long long sortingId_;
    
      // some other vars
    
        Entry( double cost, float id )
            : cost_( cost ), id_( id ), sortingId_( 1e9*100*cost + id )
        {} 
    };
    

    Adjust sortingId_ value based on what you can assume about the value ranges.

    Then, now just sort on sortingId_.


    Or as variation of the same idea, if you can't make suitable assumptions about the data, then consider preparing data especially for memcmp.


    For a higher level solution, remember that std::set::insert has an overload with a hint argument. If your data is already in near sorted order, that might seriously reduce the number of calls to your comparator function.


    And you might consider whether a std::unordered_set might be sufficient? I.e. whether you need to list the data in sorted order. Or if the sorting is just the internal stuff of std::set element insertion.


    Finally, for other readers (the OP has made clear that he's aware of this), remember to MEASURE.

提交回复
热议问题