Gaijinco wrote:
Every now and then and found two ways to resolve a problem. I try to
find a way to decide which one is best (at least speed-wise) but I
don't know how do I test how long those it take a program to run?
Several points:
* Generally speaking, given two pieces of code that solve the same
problem, you should keep the one that is the most portable,
maintainable, and extensible. Speed should not be a primary
consideration unless the piece of code is a *known* bottleneck (see the
next two points).
* You can use a profiler to calculate how long a particular piece of
code takes to run, and more importantly, you use a profiler to find out
if that piece of code is a bottleneck. There is no sense in optimizing
(or recoding in assembler or whatever) when a working, unoptimized
piece of code meets the requirements. Check your platform or
development documentation for more information on profiling on your
system.
* Beware Premature Optimization (from
http://gotw.ca/publications/mill09.htm):
'If you're a regular reader of this column, you'll already be familiar
with my regular harangues against premature optimization. The rules
boil down to: "1. Don't optimize early. 2. Don't optimize until you
know that it's needed. 3. Even then, don't optimize until you know what
needed, and where."
'By and large, programmers--that includes you and me--are notoriously
bad at guessing the actual space/time performance bottlenecks in their
own code. If you don't have performance profiles or other empirical
evidence to guide you, you can easily spend days optimizing something
that doesn't need optimizing and that won't measurably affect runtime
space or time performance. What's even worse, however, is that when you
don't understand what needs optimizing you may actually end up
pessimizing (degrading your program) by of saving a small cost while
unintentionally incurring a large cost. Once you've run performance
profiles and other tests, and you actually know that a particular
optimization will help you in your particular situation, then it's the
right time to optimize.'
Cheers! --M