Created
August 25, 2011 21:53
-
-
Save pkmital/1172090 to your computer and use it in GitHub Desktop.
seeing if stl vector really keeps data contiguous
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <vector> | |
#include <iostream> | |
using namespace std; | |
typedef float T; | |
int main() | |
{ | |
int data_size = 512; | |
vector<T *> data; | |
int num_data = 512; | |
for(int i = 0; i < num_data; i++) | |
{ | |
T * el = (T *)malloc(sizeof(T) * data_size); | |
for(int j = 0; j < data_size; j++) | |
{ | |
el[j] = i*data_size + j; | |
} | |
data.push_back(el); | |
} | |
bool isItContiguous = true; | |
T * ptr = data[0]; | |
for(int i = 0; i < num_data; i++) | |
{ | |
for(int j = 0; j < data_size; j++) | |
{ | |
if( *(ptr+i*data_size+j) != data[i][j] ) | |
{ | |
cout << i << "," << j << ": " << *(ptr+i*data_size+j) << "," << data[i][j] << " " << endl; | |
isItContiguous = false; | |
break; | |
} | |
} | |
if(!isItContiguous) | |
break; | |
} | |
if(isItContiguous) | |
{ | |
printf("YES, allocated %ld kbytes contiguously.\n", sizeof(T)*data_size*num_data/1024); | |
} | |
else | |
{ | |
printf("NO\n"); | |
} | |
// free up | |
for(int i = 0; i < num_data; i++) | |
{ | |
T * el = data[i]; | |
free(el); | |
} | |
vector<vector<T > > ddata; | |
for(int i = 0; i < num_data; i++) | |
{ | |
vector<T> el; | |
el.resize(data_size); | |
for(int j = 0; j < data_size; j++) | |
{ | |
el[j] = i*data_size + j; | |
} | |
ddata.push_back(el); | |
} | |
isItContiguous = true; | |
ptr = &(ddata[0][0]); | |
for(int i = 0; i < num_data; i++) | |
{ | |
for(int j = 0; j < data_size; j++) | |
{ | |
if( *(ptr+i*data_size+j) != ddata[i][j] ) | |
{ | |
cout << i << "," << j << ": " << *(ptr+i*data_size+j) << "," << ddata[i][j] << " " << endl; | |
isItContiguous = false; | |
break; | |
} | |
} | |
if(!isItContiguous) | |
break; | |
} | |
if(isItContiguous) | |
{ | |
printf("YES, allocated %ld kbytes contiguously.\n", sizeof(T)*data_size*num_data/1024); | |
} | |
else | |
{ | |
printf("NO\n"); | |
} | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment