Re: C++ is Slow?
nw wrote:
I'm constantly confronted with the following two techniques, which I
believe often produce less readable code, but I am told are faster
therefore better. Can anyone help me out with counter examples and
arguments?
1. The STL is slow.
More specifically vector. The argument goes like this:
"Multidimensional arrays should be allocated as large contiguous
blocks. This is so that when you are accessing the array and reach the
end of a row, the next row will already be in the cache. You also
don't need to spend time navigating pointers when accessing the array.
So a 2 dimensional array of size 100x100 should be created like this:
const int xdim=100;
const int ydim=100;
int *myarray = malloc(xdim*ydim*sizeof(int));
and accessed like this:
myarray[xdim*ypos+xpos] = avalue;
Is this argument reasonable? (Sounds reasonable to me, though the
small tests I've performed don't usually show any significant
difference).
If the tests you've performed don't show any significant difference,
then the argument is not reasonable. The only reasonable argument
is the results of the test and your standards for significance.
To me this syntax looks horrible, am I wrong? Is vector the wrong
container to use? (My usual solution would be a vector<vector<int> >).
Would using a valarray help?
You can wrap your N-dimensional dynamic memory in a class and
add an overloaded operator () with N arguments, which will make
the syntax more acceptable.
2. iostream is slow.
I've encountered this is work recently. I'd not considered it before,
I like the syntax and don't do so much IO generally... I'm just now
starting to process terabytes of data, so it'll become an issue. Is
iostream slow? specifically I encountered the following example
googling around. The stdio version runs in around 1second, the
iostream version takes 8seconds. Is this just down to a poor iostream
implementation? (gcc 4 on OS X).
Most likely.
Or are there reasons why iostream is
fundamentally slower for certain operations?
There is no reason, AFAICT.
Are there things I should
be keeping in mind to speed up io?
The fewer conversions the better.
// stdio version
#include <cstdio>
using namespace std;
const int NULA = 0;
int main (void) {
for( int i = 0; i < 100000000; ++i )
printf( "a" );
return NULA;
}
//cout version
#include <iostream>
using namespace std;
const int NULA = 0;
int main (void) {
std::ios_base::sync_with_stdio(false);
for( int i = 0; i < 100000000; ++i )
cout << "a" ;
return NULA;
}
V
--
Please remove capital 'A's when replying by e-mail
I do not respond to top-posted replies, please don't ask