私が読んだことと、メモリ構造の仕組みを理解する方法から、ベクトルはすべての値がお互いに並べられた配列を作成し、私が下にまとめたリンクリストは、次のオブジェクトが割り当てられるメモリ内のランダムなポイントを指します。したがって、このコードではベクトルがより速くなるはずです。CスタイルのリンクリストとC++のstd :: vectorとの大きな違い
次のコードをコンパイルすると、リンクされたリストのランタイムが4秒になりますが、ベクトルは21秒で実行され、ベクトルの速度は5倍になります。
ここに何か不足していますか?それとも誰か説明がありますか?ここで
#include <vector>
#include <iostream>
#include <ctime>
using namespace std;
struct point{
float t;
float v;
};
struct pointlist{
float t;
float v;
struct pointlist *next;
};
void fillpoints(std::vector<struct point> &points, struct pointlist *pointlist) {
int i;
for (i = 0; i<8;i++) {
struct point newpoint; // Fill vector
newpoint.t = (float)i;
newpoint.v = (float)i/2;
points.push_back(newpoint);
pointlist->t = (float)i; // Fill linked list
pointlist->v = (float)i/2;
struct pointlist *temppoint = (struct pointlist *)malloc(sizeof(struct pointlist));
pointlist->next = temppoint;
pointlist = temppoint;
}
struct point newpoint;
newpoint.t = 0;
newpoint.v = (float)i/2;
points.push_back(newpoint);
pointlist->t = 0;
pointlist->v = (float)i/2;
pointlist->next = NULL;
}
float areavec(std::vector<struct point> pointlist) {
float y1, z1, y2, z2, area;
area = 0;
y2 = pointlist[0].t - pointlist[0].v;
z2 = pointlist[0].t + pointlist[0].v;
for (unsigned int i = 1; i<pointlist.size();i++) {
y1 = y2;
z1 = z2;
y2 = pointlist[i].t - pointlist[i].v;
z2 = pointlist[i].t + pointlist[i].v;
area += (y1*z2) - (y2*z1);
}
return area;
}
float arealist(struct pointlist *pointlist) {
float y1, z1, y2, z2, area;
area = 0;
y2 = pointlist->t - pointlist->v;
z2 = pointlist->t + pointlist->v;
while (pointlist->next != NULL) {
y1 = y2;
z1 = z2;
y2 = pointlist->next->t - pointlist->next->v;
z2 = pointlist->next->t + pointlist->next->v;
area += (y1*z2) - (y2*z1);
pointlist = pointlist->next;
}
return area;
}
void main() {
int runs = 200000000;
float a;
std::vector<struct point> points;
struct pointlist *pointlist = (struct pointlist *)malloc(sizeof(struct pointlist));
struct pointlist *test = pointlist;
fillpoints(points, pointlist);
clock_t start = clock();
for (int i=0; i<runs; i++) {
a = arealist(pointlist);
}
cout << "Time: " << (clock()-start)/CLOCKS_PER_SEC << " Area: " << a << endl;
start = clock();
for (int i=0; i<runs; i++) {
a = areavec(points);
}
cout << "Time: " << (clock()-start)/CLOCKS_PER_SEC << " Area: " << a << endl;
cin.get();
}
あなたのリストを代わりに 'std :: list'と比較してみませんか?また、ベクトルのインデックスの代わりにイテレータを使用するとき、または最適化をオンにしたときに時間を計ったことがありますか? –
トラバース要素の速度を測定しようとしている場合は、リストを通常8つの要素よりもはるかに大きくする必要があります(ただし、プログラムのリストに通常含まれるサイズでない限り)。 –