Valarray Vs. Array Matrix-calculation Performance
Join the DZone community and get the full member experience.
Join For FreeDemonstrates the usage of valarray and measures the performance of some arithmetic operations on matriced to be compared with the same operations performed with ordinary arrays.
#include
#include
#include
#include
#include
using namespace std;
void rndm(float& a);
void zerocheck(float& a);
double duration(vector::iterator start, vector::iterator stop);
int main()
{
int i(0);
int p(0);
float k(5.3235),l(9.212);
int size(4000000);
vector vstart;
vector vstop;
vector::iterator istartclock;
vector::iterator istopclock;
vector vfloat(size);
vector::iterator ifloat;
valarray valfloat(size);
cout << "Filling float array with " << size << " random elements" << endl;
cout << "(each element needs " << sizeof(float) << " bytes of memory, so " \
<< "we need to make use of " << size*sizeof(float)/1000000<< "MBytes.)"<< endl;
// ======================= ORDINARY OPERATIONS =======================
// fill array
vstart.push_back(clock());
// vfloat.resize(size);
ifloat=vfloat.begin();
for_each(vfloat.begin(),vfloat.end(),rndm);
vstop.push_back(clock());
cout << "****** Phase 1: Math. operations on ordinary array" << endl;
// Add k to each element
cout << "*** Adding " << k << " to each element " ;
cout << "(10th element was: " << *(ifloat+10) ;
vstart.push_back(clock());
for (i=0; i::iterator start,
vector::iterator stop
)
{
return difftime(*stop,*start) ;
}
Data structure
Opinions expressed by DZone contributors are their own.
Comments