3

我刚刚开始实现我自己的向量类,我正在用一个简单的文件对其进行测试,以检查完成所需的时间。一项测试用时 2:30 分钟,而其他测试用时 90 和 29 秒。

有什么东西影响了这门课的表现。你能帮我追查源头吗?

考试:

#include "MyVector.h"

const unsigned int SIZE_V= 1000000;
const unsigned int RUNS= 10000;

int main() {

      MyVector v(SIZE_V);

      for (unsigned int j=0; j<RUNS; ++j) {
        for (unsigned int i=0; i<SIZE_V; ++i) {
          v[i]= i;
        }
      }

      return 0;
}

班上:

MyVector.h:

#ifndef MY_VECTOR_H
#define MY_VECTOR_H

class MyVector {

 public:

      MyVector(unsigned int size);
      ~MyVector();

      int& operator[](unsigned int i);

 private:
      int* _data;
      unsigned int _size;
      MyVector(const MyVector&);
      MyVector& operator=(const MyVector&);

};
#endif

MyVector.cpp:

#include "MyVector.h"
#include <assert.h>

MyVector::MyVector(unsigned int size) : _data(new int[size]) {
}

MyVector::~MyVector() {
      delete[] _data;
}

int& MyVector::operator[](unsigned int i) {
      assert(i<_size);
      return _data[i];
}

编辑:

这些是测试结果:

granularity: each sample hit covers 4 byte(s) for 0.04% of 27.09 seconds

index % time    self  children    called     name
                                                 <spontaneous>
[1]    100.0   12.51   14.58                 main [1]
               11.28    0.00 1410065408/1410065408     MyVector::operator[](unsigned int) [2]
                3.31    0.00       1/1           MyVector::~MyVector() [3]
                0.00    0.00       1/1           MyVector::MyVector(unsigned int) [7]
-----------------------------------------------
               11.28    0.00 1410065408/1410065408     main [1]
[2]     41.6   11.28    0.00 1410065408         MyVector::operator[](unsigned int) [2]
-----------------------------------------------
                3.31    0.00       1/1           main [1]
[3]     12.2    3.31    0.00       1         MyVector::~MyVector() [3]
-----------------------------------------------
                0.00    0.00       1/1           main [1]
[7]      0.0    0.00    0.00       1         MyVector::MyVector(unsigned int) [7]
-----------------------------------------------
4

3 回答 3

2

您可能想做的一件事是operator[]内联。当我这样做时,你的代码在我的盒子上的性能提高了三倍

real    0m18.270s

real    0m6.030s

在后一个测试中,测试循环的每次迭代大约需要 0.6ns (!) 或大约 1.5 个时钟周期。

这是在使用 g++ 4.7.2 和-O3.

PS代码中有一个错误:构造函数没有初始化_size,因此assert()具有未定义的行为。

于 2013-01-24T09:52:59.460 回答
1
  1. 在没有运行探查器的情况下进行测量。

  2. 测量完全优化的代码:g++ -O3

于 2013-01-24T10:00:51.220 回答
0

你在写:-

1000000 * 10000 * 4 * 8 = 320000000000

总共的数据位,在测试中是:-

2.5 mins = 2133333333 bits / sec = ~2,000 MB/s

90 secs = 3555555555 bits / sec = ~3,400 MB/s

30 secs = 10666666666 bits / sec = ~10,000 MB/s

DDR2 峰值数据速率介于 3,200 MB/s 和 8,533 MB/s 之间,DDR3 峰值数据范围介于 6,400 MB/s 和 17,066 MB/s 之间/

基于此,我会说你有 DDR3-1600 内存芯片。

于 2013-01-24T09:40:45.403 回答