Re: Improving efficiency of algorithm
* Comp1597@yahoo.co.uk:
I have a function with signature: unsigned f(unsigned);
Unless f does some bitlevel stuff I recommend using plain 'int', not 'unsigned'.
My task is to read positive integers from a file (call each number x)
and to write f(x) on standard output
My code goes like this:
BEGINNING OF CODE
unsigned ComputeThis;
// ReadFromThisFile is a stream bound to a text file
while (ReadFromThisFile >> ComputeThis)
std::cout << f(ComputeThis)<<"\n";
END OF CODE
'ReadFromThisFile', being an imperative, is IMHO ungood as a name for a stream.
Instead use something like 'NumberStream', a *descriptive* name.
Assume that the text file is very large. Can anyone suggest
strategies to improve the efficiency of this code in terms of either
caching values of ComputeThis that occur often, or speeding up the
stream reading and writing process?
Generally that's done by buffering.
I'm not very familiar with iostreams because I really hate them (for reasons
discussed earlier and too much to discuss here), but the general idea for such
speedup is to increase the stream's buffer size. Which as I recall is not very
easy with iostreams. However, it's easy with a FILE*.
Or other efficiency gains?
You should turn off sync_with_stdio.
Feel free to suggest general ideas or areas or computer science/ c++
to study that are relevant to this problem
The most important is the question of when to (not) optimize.
First of all make sure that your code is *correct*.
Don't care about micro level performance at this point, just make really sure
that it is correct. That means, among other things, /writing/ a clear-cut
technical specification, /creating/ automated tests and manual reproducible test
procedures, and doing them, and not the least, and I mean place that at the
front of issues to deal with, the /reality check/ of whether your program really
solves the higher level problem it's meant to solve (in your case there's
probably not a customer but in general, before spending zillions on development
make sure that what's developed will actually serve the customer's needs and not
introduce new severe problems, present and projected to future).
Then, before doing anything else except "known measures" that should be done as
a matter of course such as the one mentioned above, *measure*.
If performance is adequate, do nothing.
Cheers & hth.,
- Alf
--
Due to hosting requirements I need visits to <url: http://alfps.izfree.com/>.
No ads, and there is some C++ stuff! :-) Just going there is good. Linking
to it is even better! Thanks in advance!