Is std::vector so much slower than plain arrays?

后端 未结 22 2647
南方客
南方客 2020-11-22 12:00

I\'ve always thought it\'s the general wisdom that std::vector is \"implemented as an array,\" blah blah blah. Today I went down and tested it, and it seems to

22条回答
  •  不要未来只要你来
    2020-11-22 12:20

    By the way the slow down your seeing in classes using vector also occurs with standard types like int. Heres a multithreaded code:

    #include 
    #include 
    #include 
    #include 
    #include 
    #include 
    #include 
    #include 
    #include 
    using namespace std;
    
    //pthread_mutex_t map_mutex=PTHREAD_MUTEX_INITIALIZER;
    
    long long num=500000000;
    int procs=1;
    
    struct iterate
    {
        int id;
        int num;
        void * member;
        iterate(int a, int b, void *c) : id(a), num(b), member(c) {}
    };
    
    //fill out viterate and piterate
    void * viterate(void * input)
    {
        printf("am in viterate\n");
        iterate * info=static_cast (input);
        // reproduce member type
        vector test= *static_cast*> (info->member);
        for (int i=info->id; inum)
        {
            //printf("am in viterate loop\n");
            test[i];
        }
        pthread_exit(NULL);
    }
    
    void * piterate(void * input)
    {
        printf("am in piterate\n");
        iterate * info=static_cast (input);;
        int * test=static_cast (info->member);
        for (int i=info->id; inum) {
            //printf("am in piterate loop\n");
            test[i];
        }
        pthread_exit(NULL);
    }
    
    int main()
    {
        cout<<"producing vector of size "< vtest(num);
        cout<<"produced  a vector of size "<member=&pint;
            ans=pthread_create(&thread[i], NULL, piterate, (void*) it[i]);
        }
        for (int i=0; i

    The behavior from the code shows the instantiation of vector is the longest part of the code. Once you get through that bottle neck. The rest of the code runs extremely fast. This is true no matter how many threads you are running on.

    By the way ignore the absolutely insane number of includes. I have been using this code to test things for a project so the number of includes keep growing.

提交回复
热议问题