1

I use google benchmark test the performance of array and vector

link:

https://quick-bench.com/q/ixWRn2XG8Q1-OnSFP6GXsadsw_g and you can see the code with the link

result:

enter image description here it shows that use array is almost no cost, array is 2900000000 times faster than vector ### question so why this happens?

my code

#include<vector>
#include <vector>
static void int_use_array(benchmark::State& state) {
    for (auto _ : state) {
        int a[200][200];
        for(int i = 0; i < 200; ++i) {
            for(int j = 0; j < 200; ++j) {
                a[i][j] = i * j;
            }
        }
        int t = a[2][89];
    }
}
BENCHMARK(int_use_array);
static void int_use_vector(benchmark::State& state) {
    for (auto _ : state) {
        std::vector<std::vector<int> > vec(200, std::vector<int>(200, 0));
        for (int i = 0; i < 200; ++i) {
            for(int j = 0; j < 200; j++) {
                vec[i][j] = i * j;
            }
         }
        int t = vec[2][98];
    }
}
BENCHMARK(int_use_vector);
崔志强
  • 11
  • 1
  • Does this answer your question? https://stackoverflow.com/questions/15718262/what-exactly-is-the-as-if-rule – 463035818_is_not_an_ai Oct 20 '21 at 12:23
  • Your `int_use_array` function gets completely optimized out if you take a look at the "Assembly" tab - there is nothing being run at all – UnholySheep Oct 20 '21 at 12:25
  • 1
    FYI: adding `benchmark::DoNotOptimize(t);` into `int_use_array` will produce some more meaningful result – UnholySheep Oct 20 '21 at 12:32
  • 1
    just like UnholySheep said, the function int_use_array is completely optimized out. And adding benchmark::DoNotOptimize(t); works. Thank U – 崔志强 Oct 20 '21 at 12:38

0 Answers0