why is c++ std::max_element so slow?

前端 未结 3 2118
失恋的感觉
失恋的感觉 2021-01-31 02:30

I need to find the max element in the vector so I\'m using std::max_element, but I\'ve found that it\'s a very slow function, so I wrote my own version and manage t

3条回答
  •  深忆病人
    2021-01-31 03:30

    It's a simple issue of cache. To wit, the first time you load memory, in this case the contents of the vector, it's always considerably slower than if it's been recently accessed. I copied and pasted your code with GCC 4.9.

    When the functions are reversed, the ratio is 1. When they're in the original order, the ratio is 1.6.

    This still seems like a fundamental misoptimization by GCC in the case of max_element to me. However, your function times are so low, they will be dominated by CPU noise like the above cache effects, instead of any meaningful comparison.

    Reversed, Original

提交回复
热议问题