速度:通过指针调用还是通过向量访问?

时间:2012-02-01 02:38:33

标签: c++ performance pointers

我想知道哪种解决方案可以更快。让我们说我们有100个(或n个)指向B对象的mB向量,每个指针包含一个返回double值的foo():

代码1:

int main () {
    vector<double> mA;
    for (int i=0; i<100; i++)
        mA.push_back(mB->at(i)->foo());
    for (int i=0; i<100; i++)
        double a = pow((mA.at(i))*(mA.at(i+1)),2);

    return 0;
}

代码2:

int main () {
     for (int i=0; i<100; i++)
         double a = pow((mB->at(i)->foo()))*(mB->at(i+1)->foo())),2);

     return 0;
}

代码1首先将double存储在向量中,因此我们有100个通过指针调用函数,然后100 + 100访问向量mA。在第二个中,我们有100 + 100通过pointes调用函数。

1)通过指针调用比访问.at()更慢吗? 2)哪种解决方案更适合获得更快的代码? 谢谢

3 个答案:

答案 0 :(得分:0)

只看代码,第一个代码片段有2个for循环到100,第二个循环只有1 for循环,第一个代码可能会慢一些。 原因?如果检查超级慢,并且for循环有一堆它们。因此,第一个代码片段的if量是if的两倍。所以,我认为你提到的两种访问方式之间的区别不会起到重要作用。

你可以尝试做的是查看两者生成的程序集,或者你可以使用多种计时功能之一。既然你有visual studio,你可以试试QueryPerformanceCounter: http://support.microsoft.com/kb/815668

试试并告诉我们结果!

PS。我建议改变你的问题的标题,因为你说的是​​“速度”,这是不正确的,因为你正在比较速度。可能更好的问一个问题的方法是“哪个更快,访问......等等”,但我不想改变太多。

答案 1 :(得分:0)

感谢您的建议,我试过了:

#include <iostream>
#include <vector>
#include "A.h"
#include "B.h"
#include <Windows.h>
 using namespace std;

void StartTimer( _int64 *pt1 )
{
   QueryPerformanceCounter( (LARGE_INTEGER*)pt1 );
}

double StopTimer( _int64 t1 )
{
   _int64 t2, ldFreq;
   QueryPerformanceCounter( (LARGE_INTEGER*)&t2 );
   QueryPerformanceFrequency( (LARGE_INTEGER*)&ldFreq );
   return ((double)( t2 - t1 ) / (double)ldFreq) * 1000.0;
}

int main(){
_int64 t1;
StartTimer( &t1 );

 vector<B*> *mB = new vector<B*>;
for (int i=0; i<100; i++)
 mB->push_back(new B());
 A mA(mB);

 printf( "Time = %.3f\n", StopTimer( t1 ));

 system("Pause");
 return 0;
 }

A.cpp:

#include "A.h"

A::A(vector<B*> *mB)
{
 //code1:
 vector<double> mA;
 for (int i=0; i<100; i++)
  mA.push_back(mB->at(i)->foo());
  for (int i=0; i<99; i++)
  cout <<pow((mA.at(i))*(mA.at(i+1)),2)<<endl;
  //code 2:
  //for (int i=0; i<99; i++)
 //cout <<pow((mB->at(i)->foo())*(mB->at(i+1)->foo()),2)<<endl;

}

A::~A(void){}

B.cpp

#include "B.h"

B::B(void):value(10){} //firstly i used rand() maybe affects speed test
B::~B(void){}
double B::foo(){
return value;
 }

速度方面的结果不明确,因为每次调试启动时间都会有所不同,两个代码都会在20到50毫秒之间反弹

编辑: 100000 objs: 代码1:~958毫秒 代码2:~760毫秒

答案 2 :(得分:0)

以下代码段应该比您的两个版本都快,因为at()确实绑定了检查,而operator[]则没有。后者可能导致访问向量的边界,因此是条件。

if (mB->size() >= 101)
    for (size_t i = 0; i < 100; i++)
        double a = (*mB)[i]->foo() * (*mB)[i]->foo();