测量静态绑定呼叫和动态绑定呼叫之间的速度差异?

时间:2015-10-16 18:28:45

标签: c++ dynamic time static

我正在尝试测量静态绑定呼叫和动态绑定呼叫之间的速度差异,但时间到处都是。有时静态调用更快,有时动态绑定调用更快。我这样做错了吗?我的印象是帽子静态调用比动态绑定调用更快。

主要

#include "Parent.h"
#include "Child.h"
#include <iostream>
#include <ctime>

using namespace std;

int main()
{
    int choice = 1;
    do
    {
        if(choice == 1)
        {
            Parent P;
            clock_t begin_time = clock(); 
            P.calc();
            cout << "Time for statically bound call, " << float(clock() -     begin_time) << " miliseconds.";

            Child C;
            clock_t begin_time2 = clock();
            C.calc();
            cout << endl << "Time for dynamically bound call, " << float(clock() - begin_time2) << " miliseconds." << endl << endl;
         }
         cout << "1 to go again, 2 to stop. ";
         cin >> choice;
         cout << endl;
      }while(choice != 2);

    cout << endl;
    return 0;
}

家长实施

#ifndef PARENT_H
#define PARENT_H

class Parent
{
public:

    Parent();
    virtual void calc();

protected:
    int size;
};
#endif

Parent::Parent()
{
    size = 100000;
}

void Parent::calc()
{
    vector<int> myvector;
    for(int i = 0; i < size; i++)
    {
        myvector.push_back(i);
    }
 }

儿童实施

#ifndef CHILD_H
#define CHILD_H
#include "Parent.h"

class Child: public Parent
{
public:

    Child();
    void calc();
};
#endif

Child::Child()
    :Parent()
{
}

void Child::calc()
{
    Parent::calc();
}

0 个答案:

没有答案