Everyone has written slow code so let me make an important distinction and say that code can be slow for two main reasons: 1. The operations being performed are, by nature, intensive in the
form of being either computationally-heavy or I/O-dependent.
- The code is poorly written or designed such that it is sufficiently sub-optimal that it’s inefficiency becomes noticeable.
Though code slow for the first reason is often code that cannot be
improved much, code slow due the second reason can often be
improved through various optimization techniques like algorithmic
refinement, complete reimplementation or, less frequently,
refactoring.
Tracking down the slow parts and to determine the best way to
proceed is not always easy in large or complicated programs. To
assist in such performance analysis, there are numerous
profilers
available (but, as usual, Mac users should beware of
foul play).
For Ruby, there is the
profiler module
which enables automatic profile reports to be generated at the
conclusion of a program’s run. When running quick analyses, you can
enable profiling by telling the interpreter to require the profiler
module at load-time with the -r command-line flag. If your
program is contained in a file called program.rb, then you’d want
to run ruby -r profiler program.rb while being conscious that the
report is written to
standard error.
You can add a require 'profiler' to those files which you would
like profiled all the time.