Skip to content

Instantly share code, notes, and snippets.

@pkmital
Created August 25, 2011 21:53
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save pkmital/1172090 to your computer and use it in GitHub Desktop.
Save pkmital/1172090 to your computer and use it in GitHub Desktop.
seeing if stl vector really keeps data contiguous
#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