C++ Vector appear to be faster than C Array (Time). Why ?

不打扰是莪最后的温柔 提交于 2019-12-25 07:21:40

问题


Hello I have seen that C++ Vector vs Array (Time). On my mac the vector take times to be defined but after the comparison give vector for winner. How it works ? I was said int[] are faster than dynamic vector ?

#include <iostream>
#include <vector>
using namespace std;
#define N (100000000)
//int sd[N];
int main() {
    clock_t start;
    double temps;
    static int sd[N];
    start = clock();
    for (unsigned long i=0 ; i < N ; i++){
        if(sd[i]==3)
            ;
    }
    temps = (clock() - start) / (double)(CLOCKS_PER_SEC / 1000);
    printf("Time: %f ms\n",temps);
    vector<int>vd(N);
    start = clock();
    for (unsigned long i=0 ; i < N ; i++){
        if(vd[i]==3)
            ;
    }
    temps = (clock() - start) / (double)(CLOCKS_PER_SEC / 1000);
    printf("Time: %f ms\n",temps);
    while (1)
        ;
    return 0;
}

I have those results :

  • Time: 422.87400 ms
  • Time: 300.84700 ms
    Even if it begining with vector, vector appear to be faster than c array.

Thank You for your explaination.

Another question : in xcode, why i see memory used by declation vector and for static c array I have to go all the memory cells as in the code (for ... if(sd[i]...)

Thank You for your explaination.


回答1:


I have remarqued that if i initialize all the c array cells at 0 (for example or 6...) the c array will be faster or equal vector.

int main() {
    clock_t start;
    double temps;
    static int sd[N];
    for (unsigned long i=0 ; i < N ; i++){
        sd[i]=0;
    }

    start = clock();
    //puts("initialized");
    for (unsigned long i=0 ; i < N ; i++){
        if(sd[i]==3)
            ;
    }
    temps = (clock() - start) / (double)(CLOCKS_PER_SEC / 1000);
    printf("Time: %f ms\n",temps);
    //puts("initialized");
    vector<int>vd(N);
    start = clock();
    for (unsigned long i=0 ; i < N ; i++){
        if(vd[i]==3)
            ;
    }
    temps = (clock() - start) / (double)(CLOCKS_PER_SEC / 1000);
    printf("Time: %f ms\n",temps);

    while (1)
        ;
    return 0;
}

And I will see the memory used in xcode with the initialization at 0 of all cells c array.
So another question , why it is more rapid when you initialize in this case (or in general) ?



来源:https://stackoverflow.com/questions/40202324/c-vector-appear-to-be-faster-than-c-array-time-why

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!