【问题标题】:C-style Arrays vs std::vector using std::vector::at, std::vector::operator[], and iteratorsC 样式数组与使用 std::vector::at、std::vector::operator[] 和迭代器的 std::vector
【发布时间】:2020-08-20 23:34:39
【问题描述】:

我有一个应用程序,我必须使用带有目标索引列表的第三个数组 (map) 将数据从一个数组 (input) 移动到另一个数组 (output)。以一种简化的方式,我想做类似output[i] = input[ map[i] ] 的事情。

我进行了以下测试以尝试估计在使用 C 样式数组和 std::vector 之间以及在 std::vector 使用不同运算符和迭代器的情况下哪个会给我带来更好的性能。我知道运营商std::vector::at() 在进行边界检查时会降低性能,我想估计这会造成多少性能损失,以确定它是否值得。

我编写了一个示例应用程序,其中我使用不同的结构和运算符移动数据。我使用gprof 在Linux 下对其进行分析。

这是应用程序源代码(test.cpp):

#include <iostream>
#include <vector>
#include <assert.h>
#include <limits.h>

// Input and output vector size
const std::size_t vector_size    = 4096;
// Size of the map vector. This value must be
// <= 'vector_size'
const std::size_t map_size      = 2000;
// Number of iteration for each algorithm
const std::size_t num_iterations = 1000000;

// Algorithms
void __attribute__ ((noinline)) map_c_array(int *in, std::size_t *map, int *out)
{
    for (std::size_t j {0}; j < map_size; j++)
        out[j] = in[map[j]];
}

void __attribute__ ((noinline)) map_vector_v1(const std::vector<int> &in, const std::vector<std::size_t> &map, std::vector<int> &out)
{
    std::size_t j {0};
    for (auto const& m : map)
        out.at(j++) = in.at(m);
}

void __attribute__ ((noinline)) map_vector_v2(const std::vector<int> &in, const std::vector<std::size_t> &map, std::vector<int> &out)
{
    for (std::size_t j{0}; j < map_size; ++j)
        out.at(j) = in.at(map.at(j));
}

void __attribute__ ((noinline)) map_vector_v3(const std::vector<int> &in, const std::vector<std::size_t> &map, std::vector<int> &out)
{
    std::size_t j {0};
    for (auto const& m : map)
        out[j++] = in[m];
}

void __attribute__ ((noinline)) map_vector_v4(const std::vector<int> &in, const std::vector<std::size_t> &map, std::vector<int> &out)
{
    for (std::size_t j{0}; j < map_size; ++j)
        out[j] = in[map[j]];
}

void __attribute__ ((noinline)) map_vector_v5(const std::vector<int> &in, const std::vector<std::size_t> &map, std::vector<int> &out)
{
    std::vector<int>::const_iterator inIt  { in.begin() };
    std::vector<int>::iterator       outIt { out.begin() };
    for (std::vector<std::size_t>::const_iterator mapIt { map.begin() }; mapIt != map.end(); ++mapIt)
        *outIt++ = *(inIt + *mapIt);
}

void __attribute__ ((noinline)) map_vector_v6(const std::vector<int> &in, const std::vector<std::size_t> &map, std::vector<int> &out)
{
    std::vector<int>::const_iterator inIt  { in.begin() };
    std::vector<int>::iterator       outIt { out.begin() };
    for (auto const& m : map)
        *outIt++ = *(inIt + m);
}

// Main program
int main(int argc, char *argv[])
{
    // Run the algorithm based on vectors
    for (std::size_t k {0}; k < 6; ++k)
    {
        // Input vector. It is of size = 'vector_size'
        std::vector<int> in(vector_size, 0);

        // Output vector. It is of size = 'vector_size'
        std::vector<int> out(vector_size, 0);

        // Mask Vector. I want to do out[i] = in[ map[i] ]
        // Its values are indexes of the 'in' vector, so they all need
        // to be less than or equal to 'vector_size'
        // It is of size = 'map_size'. To each value in this vector there will
        // be a corresponding value in the 'out' vector. So, 'map_size' need to
        // be less than or equal to 'vector_size'.
        std::vector<std::size_t> map(map_size, 0);


        // Fill input vector with random numbers
        for (std::size_t i {0}; i < vector_size; ++i)
            in.at(i) = static_cast<int>( static_cast<float>(rand())/RAND_MAX * INT_MIN );

        // Fill the map vector with random number, not greater that the
        // maximum size of the in and out vectors.
        for (std::size_t i {0}; i < map_size; ++i)
            map.at(i) = static_cast<std::size_t>( static_cast<float>(rand())/RAND_MAX * vector_size );

        // Copy the values using each algorithm
        switch (k)
        {
            case 0:
                for (std::size_t i {0}; i < num_iterations; ++i )
                {
                    map_vector_v1(in, map, out);

                    // Verify that the values were copied correctly
                    for (std::size_t i {0}; i < map_size; ++i)
                      assert( out[i] == in[map[i]] );
                }
                break;
            case 1:
                for (std::size_t i {0}; i < num_iterations; ++i )
                {
                    map_vector_v2(in, map, out);

                    // Verify that the values were copied correctly
                    for (std::size_t i {0}; i < map_size; ++i)
                      assert( out[i] == in[map[i]] );
                }
                break;
            case 2:
                for (std::size_t i {0}; i < num_iterations; ++i )
                {
                    map_vector_v3(in, map, out);

                    // Verify that the values were copied correctly
                    for (std::size_t i {0}; i < map_size; ++i)
                      assert( out[i] == in[map[i]] );
                }
                break;
            case 3:
                for (std::size_t i {0}; i < num_iterations; ++i )
                {
                    map_vector_v4(in, map, out);

                    // Verify that the values were copied correctly
                    for (std::size_t i {0}; i < map_size; ++i)
                      assert( out[i] == in[map[i]] );
                }
                break;
            case 4:
                for (std::size_t i {0}; i < num_iterations; ++i )
                {
                    map_vector_v5(in, map, out);

                    // Verify that the values were copied correctly
                    for (std::size_t i {0}; i < map_size; ++i)
                      assert( out[i] == in[map[i]] );
                }
                break;
            case 5:
                for (std::size_t i {0}; i < num_iterations; ++i )
                {
                    map_vector_v6(in, map, out);

                    // Verify that the values were copied correctly
                    for (std::size_t i {0}; i < map_size; ++i)
                      assert( out[i] == in[map[i]] );
                }
                break;
        }

    }

        // Finally, run the algorithm based on C arrays
    {
        // Input vector. It is of size = 'vector_size'
        int in[vector_size];

        // Output vector. It is of size = 'vector_size'
        int out[vector_size];

        // Mask Vector. I want to do out[i] = in[ map[i] ]
        // Its values are indexes of the 'in' vector, so they all need
        // to be less than or equal to 'vector_size'
        // It is of size = 'map_size'. To each value in this vector there will
        // be a corresponding value in the 'out' vector. So, 'map_size' need to
        // be less than or equal to 'vector_size'.
        std::size_t map[map_size];


        // Fill input vector with random numbers
        for (std::size_t i {0}; i < vector_size; ++i)
            in[i] = static_cast<int>( static_cast<float>(rand())/RAND_MAX * INT_MIN );

        // Fill the map vector with random number, not greater that the
        // maximum size of the in and out vectors.
        for (std::size_t i {0}; i < map_size; ++i)
            map[i] = static_cast<std::size_t>( static_cast<float>(rand())/RAND_MAX * vector_size );

        for (std::size_t i {0}; i < num_iterations; ++i)
        {
            map_c_array(in, map, out);

            // Verify that the values were copied correctly
            for (std::size_t i {0}; i < map_size; ++i)
              assert( out[i] == in[map[i]] );
        }

    }
}

(注意:我使用noinline 属性来避免编译器内联我的函数,正如我想在gprof 中看到的那样)。

我编译它:

g++ -o test test.cpp -Wall -g -O3 -pg

然后我得到了个人资料:

gprof test

结果如下:

Flat profile:

Each sample counts as 0.01 seconds.
  %   cumulative   self              self     total
 time   seconds   seconds    calls  Ts/call  Ts/call  name
 35.42      3.29     3.29                             map_vector_v2(std::vector<int, std::allocator<int> > const&, std::vector<unsigned long, std::allocator<unsigned long> > const&, std::vector<int, std::allocator<int> >&)
 17.17      4.89     1.60                             map_vector_v1(std::vector<int, std::allocator<int> > const&, std::vector<unsigned long, std::allocator<unsigned long> > const&, std::vector<int, std::allocator<int> >&)
 11.34      5.94     1.05                             map_vector_v3(std::vector<int, std::allocator<int> > const&, std::vector<unsigned long, std::allocator<unsigned long> > const&, std::vector<int, std::allocator<int> >&)
 10.37      6.90     0.96                             map_vector_v5(std::vector<int, std::allocator<int> > const&, std::vector<unsigned long, std::allocator<unsigned long> > const&, std::vector<int, std::allocator<int> >&)
  9.72      7.81     0.90                             map_vector_v4(std::vector<int, std::allocator<int> > const&, std::vector<unsigned long, std::allocator<unsigned long> > const&, std::vector<int, std::allocator<int> >&)
  8.64      8.61     0.80                             map_c_array(int*, unsigned long*, int*)
  7.67      9.32     0.71                             map_vector_v6(std::vector<int, std::allocator<int> > const&, std::vector<unsigned long, std::allocator<unsigned long> > const&, std::vector<int, std::allocator<int> >&)
  0.00      9.32     0.00        1     0.00     0.00  _GLOBAL__sub_I__Z11map_c_arrayPiPmS_

 %         the percentage of the total running time of the
time       program used by this function.

cumulative a running sum of the number of seconds accounted
 seconds   for by this function and those listed above it.

 self      the number of seconds accounted for by this
seconds    function alone.  This is the major sort for this
           listing.

calls      the number of times this function was invoked, if
           this function is profiled, else blank.

 self      the average number of milliseconds spent in this
ms/call    function per call, if this function is profiled,
       else blank.

 total     the average number of milliseconds spent in this
ms/call    function and its descendents per call, if this
       function is profiled, else blank.

name       the name of the function.  This is the minor sort
           for this listing. The index shows the location of
       the function in the gprof listing. If the index is
       in parenthesis it shows where it would appear in
       the gprof listing if it were to be printed.


Copyright (C) 2012-2018 Free Software Foundation, Inc.

Copying and distribution of this file, with or without modification,
are permitted in any medium without royalty provided the copyright
notice and this notice are preserved.


             Call graph (explanation follows)


granularity: each sample hit covers 2 byte(s) for 0.11% of 9.32 seconds

index % time    self  children    called     name
                                                 <spontaneous>
[1]     35.3    3.29    0.00                 map_vector_v2(std::vector<int, std::allocator<int> > const&, std::vector<unsigned long, std::allocator<unsigned long> > const&, std::vector<int, std::allocator<int> >&) [1]
-----------------------------------------------
                                                 <spontaneous>
[2]     17.1    1.60    0.00                 map_vector_v1(std::vector<int, std::allocator<int> > const&, std::vector<unsigned long, std::allocator<unsigned long> > const&, std::vector<int, std::allocator<int> >&) [2]
-----------------------------------------------
                                                 <spontaneous>
[3]     11.3    1.05    0.00                 map_vector_v3(std::vector<int, std::allocator<int> > const&, std::vector<unsigned long, std::allocator<unsigned long> > const&, std::vector<int, std::allocator<int> >&) [3]
-----------------------------------------------
                                                 <spontaneous>
[4]     10.3    0.96    0.00                 map_vector_v5(std::vector<int, std::allocator<int> > const&, std::vector<unsigned long, std::allocator<unsigned long> > const&, std::vector<int, std::allocator<int> >&) [4]
-----------------------------------------------
                                                 <spontaneous>
[5]      9.7    0.90    0.00                 map_vector_v4(std::vector<int, std::allocator<int> > const&, std::vector<unsigned long, std::allocator<unsigned long> > const&, std::vector<int, std::allocator<int> >&) [5]
-----------------------------------------------
                                                 <spontaneous>
[6]      8.6    0.80    0.00                 map_c_array(int*, unsigned long*, int*) [6]
-----------------------------------------------
                                                 <spontaneous>
[7]      7.6    0.71    0.00                 map_vector_v6(std::vector<int, std::allocator<int> > const&, std::vector<unsigned long, std::allocator<unsigned long> > const&, std::vector<int, std::allocator<int> >&) [7]
-----------------------------------------------
                0.00    0.00       1/1           __libc_csu_init [21]
[15]     0.0    0.00    0.00       1         _GLOBAL__sub_I__Z11map_c_arrayPiPmS_ [15]
-----------------------------------------------

 This table describes the call tree of the program, and was sorted by
 the total amount of time spent in each function and its children.

 Each entry in this table consists of several lines.  The line with the
 index number at the left hand margin lists the current function.
 The lines above it list the functions that called this function,
 and the lines below it list the functions this one called.
 This line lists:
     index  A unique number given to each element of the table.
        Index numbers are sorted numerically.
        The index number is printed next to every function name so
        it is easier to look up where the function is in the table.

     % time This is the percentage of the `total' time that was spent
        in this function and its children.  Note that due to
        different viewpoints, functions excluded by options, etc,
        these numbers will NOT add up to 100%.

     self   This is the total amount of time spent in this function.

     children   This is the total amount of time propagated into this
        function by its children.

     called This is the number of times the function was called.
        If the function called itself recursively, the number
        only includes non-recursive calls, and is followed by
        a `+' and the number of recursive calls.

     name   The name of the current function.  The index number is
        printed after it.  If the function is a member of a
        cycle, the cycle number is printed between the
        function's name and the index number.


 For the function's parents, the fields have the following meanings:

     self   This is the amount of time that was propagated directly
        from the function into this parent.

     children   This is the amount of time that was propagated from
        the function's children into this parent.

     called This is the number of times this parent called the
        function `/' the total number of times the function
        was called.  Recursive calls to the function are not
        included in the number after the `/'.

     name   This is the name of the parent.  The parent's index
        number is printed after it.  If the parent is a
        member of a cycle, the cycle number is printed between
        the name and the index number.

 If the parents of the function cannot be determined, the word
 `<spontaneous>' is printed in the `name' field, and all the other
 fields are blank.

 For the function's children, the fields have the following meanings:

     self   This is the amount of time that was propagated directly
        from the child into the function.

     children   This is the amount of time that was propagated from the
        child's children to the function.

     called This is the number of times the function called
        this child `/' the total number of times the child
        was called.  Recursive calls by the child are not
        listed in the number after the `/'.

     name   This is the name of the child.  The child's index
        number is printed after it.  If the child is a
        member of a cycle, the cycle number is printed
        between the name and the index number.

 If there are any cycles (circles) in the call graph, there is an
 entry for the cycle-as-a-whole.  This entry shows who called the
 cycle (as parents) and the members of the cycle (as children.)
 The `+' recursive calls entry shows the number of function calls that
 were internal to the cycle, and the calls entry for each member shows,
 for that member, how many times it was called from other members of
 the cycle.


Copyright (C) 2012-2018 Free Software Foundation, Inc.

Copying and distribution of this file, with or without modification,
are permitted in any medium without royalty provided the copyright
notice and this notice are preserved.


Index by function name

  [15] _GLOBAL__sub_I__Z11map_c_arrayPiPmS_ (test.cpp) [1] map_vector_v2(std::vector<int, std::allocator<int> > const&, std::vector<unsigned long, std::allocator<unsigned long> > const&, std::vector<int, std::allocator<int> >&) [4] map_vector_v5(std::vector<int, std::allocator<int> > const&, std::vector<unsigned long, std::allocator<unsigned long> > const&, std::vector<int, std::allocator<int> >&)
   [6] map_c_array(int*, unsigned long*, int*) [3] map_vector_v3(std::vector<int, std::allocator<int> > const&, std::vector<unsigned long, std::allocator<unsigned long> > const&, std::vector<int, std::allocator<int> >&) [7] map_vector_v6(std::vector<int, std::allocator<int> > const&, std::vector<unsigned long, std::allocator<unsigned long> > const&, std::vector<int, std::allocator<int> >&)
   [2] map_vector_v1(std::vector<int, std::allocator<int> > const&, std::vector<unsigned long, std::allocator<unsigned long> > const&, std::vector<int, std::allocator<int> >&) [5] map_vector_v4(std::vector<int, std::allocator<int> > const&, std::vector<unsigned long, std::allocator<unsigned long> > const&, std::vector<int, std::allocator<int> >&)

我看到了:

  • 使用std::vector::at() 相对于std::vector:operator[]map_vector_v1map_vector_v3)时,性能影响显着,大约慢 60%。
  • 使用迭代器似乎比使用 std::vector::operator[] 快 30% 左右(map_vector_v6map_vector_v3)。
  • 我有点惊讶map_vector_v6 比使用 C 样式数组 (map_c_array) 稍微快一些。
  • 我认为map_vector_v5map_vector_v6 相当,所以我很惊讶map_vector_v6 更快。

我最初的想法是使用map_vector_v1。但现在我想我会选择map_vector_v6,以确保我的map 向量的值不会超出范围。

我想分享这个结果,以防它可以帮助其他人,或者如果我做错了什么会影响我的结果。

注意:我正在 Ubuntu 18.04 中编译和运行此代码,其中:

$ g++ --version
g++ (Ubuntu 7.5.0-3ubuntu1~18.04) 7.5.0
Copyright (C) 2017 Free Software Foundation, Inc.
This is free software; see the source for copying conditions.  There is NO
warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
$ gprof --version
GNU gprof (GNU Binutils for Ubuntu) 2.30
Based on BSD gprof, copyright 1983 Regents of the University of California.
This program is free software.  This program has absolutely no warranty.

编辑:

感谢您的所有 cmets。我对我的代码做了一些更改,比如在每次迭代中生成新的映射和输入向量,并在每次迭代结束时对输出向量进行一些操作以避免它被优化。 我还添加了第二个使用指针的 C 风格版本,结果证明它更快。

这是更新后的代码。

#include <iostream>
#include <vector>
#include <assert.h>
#include <limits.h>
#include <math.h>

// Input and output vector size
const std::size_t vector_size    = 4096;
// Size of the map vector. This value must be
// <= 'vector_size'
const std::size_t map_size      = 2000;
// Number of iteration for each algorithm
const std::size_t num_iterations = 1000000;

// Algorithms
void __attribute__ ((noinline)) map_c_array(int *in, std::size_t *map, int *out)
{
    for (std::size_t j {0}; j < map_size; j++)
            out[j] = in[map[j]];
}

void __attribute__ ((noinline)) map_c_array_v2(int *in, std::size_t *map, int *out)
{
    for (std::size_t j {0}; j < map_size; j++)
            *out++ = *(in + *map++);
}

void __attribute__ ((noinline)) map_vector_v1(const std::vector<int> &in, const std::vector<std::size_t> &map, std::vector<int> &out)
{
    std::size_t j {0};
    for (auto const& m : map)
        out.at(j++) = in.at(m);
}

void __attribute__ ((noinline)) map_vector_v2(const std::vector<int> &in, const std::vector<std::size_t> &map, std::vector<int> &out)
{
    for (std::size_t j{0}; j < map_size; ++j)
        out.at(j) = in.at(map.at(j));
}

void __attribute__ ((noinline)) map_vector_v3(const std::vector<int> &in, const std::vector<std::size_t> &map, std::vector<int> &out)
{
    std::size_t j {0};
    for (auto const& m : map)
        out[j++] = in[m];
}

void __attribute__ ((noinline)) map_vector_v4(const std::vector<int> &in, const std::vector<std::size_t> &map, std::vector<int> &out)
{
    for (std::size_t j{0}; j < map_size; ++j)
        out[j] = in[map[j]];
}

void __attribute__ ((noinline)) map_vector_v5(const std::vector<int> &in, const std::vector<std::size_t> &map, std::vector<int> &out)
{
    std::vector<int>::const_iterator inIt  { in.begin() };
    std::vector<int>::iterator       outIt { out.begin() };
    for (std::vector<std::size_t>::const_iterator mapIt { map.begin() }; mapIt != map.end(); ++mapIt)
        *outIt++ = *(inIt + *mapIt);
}

void __attribute__ ((noinline)) map_vector_v6(const std::vector<int> &in, const std::vector<std::size_t> &map, std::vector<int> &out)
{
    std::vector<int>::const_iterator inIt  { in.begin() };
    std::vector<int>::iterator       outIt { out.begin() };
    for (auto const& m : map)
        *outIt++ = *(inIt + m);
}

// Main program
int main(int argc, char *argv[])
{
    // Run algorithms based on vectors
    for (std::size_t k {0}; k < 6; ++k)
    {
        // Run 'num_itertions' iteration for each algorithm
        for (std::size_t i {0}; i < num_iterations; ++i )
        {
            // Input vector. It is of size = 'vector_size'
            std::vector<int> in(vector_size, 0);

            // Output vector. It is of size = 'vector_size'
            std::vector<int> out(vector_size, 0);

            // Mask Vector. I want to do out[i] = in[ map[i] ]
            // Its values are indexes of the 'in' vector, so they all need
            // to be less than or equal to 'vector_size'
            // It is of size = 'map_size'. To each value in this vector there will
            // be a corresponding value in the 'out' vector. So, 'map_size' need to
            // be less than or equalt to 'vector_size'.
            std::vector<std::size_t> map(map_size, 0);


            // Fill input vector with random numbers
            for (std::size_t i {0}; i < vector_size; ++i)
                in.at(i) = static_cast<int>( static_cast<float>(rand())/RAND_MAX * INT_MIN );

            // Fill the map vector with random number, not greater that the
            // maximum size of the in and out vectors.
            for (std::size_t i {0}; i < map_size; ++i)
                map.at(i) = static_cast<std::size_t>( static_cast<float>(rand())/RAND_MAX * ( vector_size - 1 ) );

            // Copy the values using each algorithm
            switch (k)
            {
                case 0:
                    map_vector_v1(in, map, out);
                    break;
                case 1:
                    map_vector_v2(in, map, out);
                    break;
                case 2:
                    map_vector_v3(in, map, out);
                    break;
                case 3:
                    map_vector_v4(in, map, out);
                    break;
                case 4:
                    map_vector_v5(in, map, out);
                    break;
                case 5:
                    map_vector_v6(in, map, out);
                    break;
            }

            // Verify that the values were copied correctly
            for (std::size_t i {0}; i < map_size; ++i)
                assert( out[i] == in[map[i]] );

            // Do some operation in the data
            for (std::size_t i {0}; i < map_size; ++i)
                out[i] += rand();
        }

    }


    // Run algorithms based on C arrays
    {
        // Run the algorithm based on vectors
        for (std::size_t k {0}; k < 2; ++k)
        {
            for (std::size_t i {0}; i < num_iterations; ++i)
            {
                // Input vector. It is of size = 'vector_size'
                int in[vector_size];

                // Output vector. It is of size = 'vector_size'
                int out[vector_size];

                // Mask Vector. I want to do out[i] = in[ map[i] ]
                // Its values are indexes of the 'in' vector, so they all need
                // to be less than or equal to 'vector_size'
                // It is of size = 'map_size'. To each value in this vector there will
                // be a corresponding value in the 'out' vector. So, 'map_size' need to
                // be less than or equalt to 'vector_size'.
                std::size_t map[map_size];


                // Fill input vector with random numbers
                for (std::size_t i {0}; i < vector_size; ++i)
                    in[i] = static_cast<int>( static_cast<float>(rand())/RAND_MAX * INT_MIN );

                // Fill the map vector with random number, not greater that the
                // maximum size of the in and out vectors.
                for (std::size_t i {0}; i < map_size; ++i)
                    map[i] = static_cast<std::size_t>( static_cast<float>(rand())/RAND_MAX * ( vector_size - 1 ) );

                // Copy the values using each algorithm
                switch (k)
                {
                    case 0:
                        map_c_array(in, map, out);
                        break;
                    case 1:
                        map_c_array_v2(in, map, out);
                        break;
                }

                // Verify that the values were copied correctly
                for (std::size_t i {0}; i < map_size; ++i)
                    assert( out[i] == in[map[i]] );

                // Do some operation in the data
                for (std::size_t i {0}; i < map_size; ++i)
                    out[i] += rand();
            }
        }

    }
}

这是我现在看到的结果:

Flat profile:

Each sample counts as 0.01 seconds.
  %   cumulative   self              self     total
 time   seconds   seconds    calls  Ts/call  Ts/call  name
 30.55      3.88     3.88                             map_vector_v2(std::vector<int, std::allocator<int> > const&, std::vector<unsigned long, std::allocator<unsigned long> > const&, std::vector<int, std::allocator<int> >&)
 17.76      6.14     2.26                             map_vector_v1(std::vector<int, std::allocator<int> > const&, std::vector<unsigned long, std::allocator<unsigned long> > const&, std::vector<int, std::allocator<int> >&)
 10.66      7.49     1.35                             map_c_array(int*, unsigned long*, int*)
  9.08      8.65     1.15                             map_vector_v5(std::vector<int, std::allocator<int> > const&, std::vector<unsigned long, std::allocator<unsigned long> > const&, std::vector<int, std::allocator<int> >&)
  8.92      9.78     1.13                             map_vector_v3(std::vector<int, std::allocator<int> > const&, std::vector<unsigned long, std::allocator<unsigned long> > const&, std::vector<int, std::allocator<int> >&)
  7.89     10.78     1.00                             map_vector_v4(std::vector<int, std::allocator<int> > const&, std::vector<unsigned long, std::allocator<unsigned long> > const&, std::vector<int, std::allocator<int> >&)
  7.89     11.79     1.00                             map_vector_v6(std::vector<int, std::allocator<int> > const&, std::vector<unsigned long, std::allocator<unsigned long> > const&, std::vector<int, std::allocator<int> >&)
  7.58     12.75     0.96                             map_c_array_v2(int*, unsigned long*, int*)
  0.00     12.75     0.00        1     0.00     0.00  _GLOBAL__sub_I__Z11map_c_arrayPiPmS_

【问题讨论】:

  • 一个带有谷歌基准的微基准似乎表明所有(除了检查的at 版本)都具有相同的性能:quick-bench.com/7NXQHXZadv-rFfRgC2lqzxQf_GU 看看是否再次运行测试/以不同的顺序会导致不同的结果。第一个暗示您的基准测试不够准确的提示是 map_vector_v5map_vector_v6 确实会编译成同一个程序集
  • 此外,您应该触摸内存,以便所有写入都真正通过,否则优化器可能会编译掉很多实际工作。小心你的基准。最终,优化器会创造奇迹。
  • std::vector::at()std::vector::operator[]() 慢一点并不奇怪,std::vector::operator[]() 又不比 C 数组 operator[] 慢。 std::vector 中的 at()[] 之间的主要区别:at() 会进行范围检查,并且可能会抛出与 [] 不同的异常,而 [] 不会。 std::vector::operator[]() 的实现可能只不过是 C 数组 operator[] 之类的包装器(还有一个额外的 assert() 用于范围检查,只有在未定义 NDEBUG 时才有效。)
  • 关于微基准我有点惊讶 map_vector_v1map_vector_v2 慢,因为后者使用运算符 std::vector::at() 3 次,而不是 2 次。我重新运行相同的测试,但添加了benchmark::DoNotOptimize 调用以避免向量被优化,我看到了不同的结果:quick-bench.com/MFQdK7x72lGLZKxnJtWDzqmRzhs。在这种情况下,map_vector_v1map_vector_v2 都是等价的,这对我来说更有意义。虽然在我的测试中我总是看到map_vector_v2 相当慢。
  • @JesusVasquez:CPU 速度没有被锁定,也没有在测试前清除内存,所以第一块代码通常会比其他代码慢。微基准测试很难。

标签: c++ arrays performance vector iterator


【解决方案1】:

谢谢大家的cmets。

我只想总结一下我的发现。

根据我上面描述的测量结果:

  • 这 3 个表单的执行时间是该组中最快的:
void map_c_array_v2(int *in, std::size_t *map, int *out)
{
    for (std::size_t j {0}; j < map_size; j++)
            *out++ = *(in + *map++);
}

void map_vector_v4(const std::vector<int> &in, const std::vector<std::size_t> &map, std::vector<int> &out)
{
    for (std::size_t j{0}; j < map_size; ++j)
        out[j] = in[map[j]];
}

void map_vector_v6(const std::vector<int> &in, const std::vector<std::size_t> &map, std::vector<int> &out)
{
    std::vector<int>::const_iterator inIt  { in.begin() };
    std::vector<int>::iterator       outIt { out.begin() };
    for (auto const& m : map)
        *outIt++ = *(inIt + m);
}
  • 紧随其后的是这 2 种形式,速度慢了约 10-15%。他们使用额外的变量来控制循环:
void  map_vector_v3(const std::vector<int> &in, const std::vector<std::size_t> &map, std::vector<int> &out)
{
    std::size_t j {0};
    for (auto const& m : map)
        out[j++] = in[m];
}

void map_vector_v5(const std::vector<int> &in, const std::vector<std::size_t> &map, std::vector<int> &out)
{
    std::vector<int>::const_iterator inIt  { in.begin() };
    std::vector<int>::iterator       outIt { out.begin() };
    for (std::vector<std::size_t>::const_iterator mapIt { map.begin() }; mapIt != map.end(); ++mapIt)
        *outIt++ = *(inIt + *mapIt);
}
  • 然后这个表单慢了大约 35%。它与更快的map_vector_v4 非常相似,不同的是map_vector_v4 使用const 引用:
void map_c_array(int *in, std::size_t *map, int *out)
{
    for (std::size_t j {0}; j < map_size; j++)
            out[j] = in[map[j]];
}
  • 这种形式的速度要慢 2 倍。这个使用了std::vector::at() 运算符,它进行额外的边界检查:
void map_vector_v1(const std::vector<int> &in, const std::vector<std::size_t> &map, std::vector<int> &out)
{
    std::size_t j {0};
    for (auto const& m : map)
        out.at(j++) = in.at(m);
}
  • 最后这是最慢的,几乎慢了 4 倍。这个也像前一种情况一样使用std::vector::at() 运算符,但它使用的次数更多(3 次而不是 2 次)
void map_vector_v2(const std::vector<int> &in, const std::vector<std::size_t> &map, std::vector<int> &out)
{
    for (std::size_t j{0}; j < map_size; ++j)
        out.at(j) = in.at(map.at(j));
}

【讨论】:

    猜你喜欢
    • 2012-05-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-09-22
    • 1970-01-01
    • 2017-02-01
    相关资源
    最近更新 更多