C++: Optimizing speed with vector/array?

前端 未结 8 1738
半阙折子戏
半阙折子戏 2021-01-02 00:51

I have a nested for-loop structure and right now I am re-declaring the vector at the start of each iteration:

void function (n1,n2,bound,etc){

    for (int          


        
8条回答
  •  执笔经年
    2021-01-02 01:29

    Here is some code that tests a few different methods.

    #include 
    #include 
    #include 
    
    int main()
    {
      typedef std::chrono::high_resolution_clock clock;
    
      unsigned n1 = 1000;
      unsigned n2 = 1000;
    
      // Original method
      {
        auto start = clock::now();
        for (unsigned i = 0; i < 10000; ++i)
        {
          std::vector> vec(n1, std::vector(n2));
          // vec is initialized to zero already
    
          // do stuff
        }
        auto elapsed_time = clock::now() - start;
    
        std::cout << elapsed_time.count() << std::endl;
      }
    
    
      // reinitialize values to zero at every pass in the loop
      {
        auto start = clock::now();
        std::vector> vec(n1, std::vector(n2));
        for (unsigned i = 0; i < 10000; ++i)
        {
          // initialize vec to zero at the start of every loop
          for (unsigned j = 0; j < n1; ++j)
            for (unsigned k = 0; k < n2; ++k)
                vec[j][k] = 0;
    
          // do stuff
        }
        auto elapsed_time = clock::now() - start;
    
        std::cout << elapsed_time.count() << std::endl;
      }
    
      // clearing the vector this way is not optimal since it will destruct the
      // inner vectors
      {
        auto start = clock::now();
        std::vector> vec(n1, std::vector(n2));
        for (unsigned i = 0; i < 10000; ++i)
        {
          vec.clear();
          vec.resize(n1, std::vector(n2));
    
          // do stuff
        }
        auto elapsed_time = clock::now() - start;
    
        std::cout << elapsed_time.count() << std::endl;
      }
    
      // equivalent to the second method from above
      // no performace penalty
      {
        auto start = clock::now();
        std::vector> vec(n1, std::vector(n2));
        for (unsigned i = 0; i < 10000; ++i)
        {
          for (unsigned j = 0; j < n1; ++j)
          {
            vec[j].clear();
            vec[j].resize(n2);
          }
    
          // do stuff
        }
        auto elapsed_time = clock::now() - start;
    
        std::cout << elapsed_time.count() << std::endl;
      }
    }
    

    Edit: I've updated the code to make a fairer comparison between the methods. Edit 2: Cleaned up the code a bit, methods 2 or 4 are the way to go.

    Here are the timings of the above four methods on my computer:

    16327389
    15216024
    16371469
    15279471
    

    The point is that you should try out different methods and profile your code.

提交回复
热议问题