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

前端 未结 3 2117
失恋的感觉
失恋的感觉 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:25

    You are probably running your test in 64-bit mode, where sizeof(int) == 4, but sizeof(std::vector<>::iterator) == 8, so that assignment in the loop to int (what my_max_element does) is faster than to std::vector<>::iterator (this is what std::max_element does).

    If you change std::vector to std::vector results change in favour to std::max_element:

    MaxIter = 1000000012
    MaxArray = 1000000012
    Total CPU time iterator = 0.00429082
    Total CPU time array = 0.00572205
    iter/array ratio: = 0.749875
    

    One important note: when benchmarking disable the CPU frequency scaling, so that the CPU does not switch gears in the middle of the benchmark.


    But I think something else is at play here, since just changing the loop variable from int to long does not change the results...

提交回复
热议问题