From what I have read, and the way I understand how memory structures work, the vector creates an array where all the values are aligned after each other, while the linked list I have put together below will point to a random point in memory where the next object is allocated. Hence the vector should be faster for this code.
When I compile the following code I get runtimes of 4 sec for the linked list, while the vector runs in 21 sec, thats a 5 times speed increase for the vector.
Am I missing something here? Or does anyone have an explanation for this?
#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();
}
Here, I’ll fix that:
You were copying the vector 200000000 times. Whereas with the linked list, you were just copying a pointer.