C ++向量似乎比C数组(时间)更快.为什么 ? [英] C++ Vector appear to be faster than C Array (Time). Why ?

查看:76
本文介绍了C ++向量似乎比C数组(时间)更快.为什么 ?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

您好,我已经看到 C ++向量与数组(时间).在我的Mac上,矢量需要花费一些时间来定义,但在比较之后将矢量提供给获胜者.这个怎么运作 ?有人说int []比动态向量还快?

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;
}

我有那些结果:

  • 时间:422.87400毫秒
  • 时间:300.84700毫秒
    即使以矢量开头,矢量似乎也比c数组要快.

谢谢您的解释.

另一个问题:在xcode中,为什么我会看到减数向量使用的内存以及对于静态c数组,我必须像代码中那样去所有内存单元(对于... if(sd [i] ...)

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]...)

谢谢您的解释.

推荐答案

我重新建议,如果我将所有c数组单元格初始化为0(例如6或...),则c数组将更快或等于向量.

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;
}

然后我将看到xcode中使用的内存,其中所有单元格c数组的初始化都为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) ?

这篇关于C ++向量似乎比C数组(时间)更快.为什么 ?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆