25.7 Extensions -- Deriving Better Profilers
The Profile class of both modules, profile and cProfile, were written so that derived classes could be developed to extend the profiler. The details are not described here, as doing this successfully requires an expert understanding of how the Profile class works internally. Study the source code of the module carefully if you want to pursue this.
If all you want to do is change how current time is determined (for example, to force use of wall-clock time or elapsed process time), pass the timing function you want to the Profile class constructor:
pr = profile.Profile(your_time_func)
The resulting profiler will then call your_time_func().
- your_time_func() should return a single number, or a list of
numbers whose sum is the current time (like what os.times()
returns). If the function returns a single time number, or the list of
returned numbers has length 2, then you will get an especially fast
version of the dispatch routine.
Be warned that you should calibrate the profiler class for the timer function that you choose. For most machines, a timer that returns a lone integer value will provide the best results in terms of low overhead during profiling. (os.times() is pretty bad, as it returns a tuple of floating point values). If you want to substitute a better timer in the cleanest fashion, derive a class and hardwire a replacement dispatch method that best handles your timer call, along with the appropriate calibration constant.
- your_time_func() should return a single number. If it returns
plain integers, you can also invoke the class constructor with a second
argument specifying the real duration of one unit of time. For example,
if your_integer_time_func() returns times measured in thousands
of seconds, you would constuct the Profile instance as follows:
pr = profile.Profile(your_integer_time_func, 0.001)
As the cProfile.Profile class cannot be calibrated, custom timer functions should be used with care and should be as fast as possible. For the best results with a custom timer, it might be necessary to hard-code it in the C source of the internal _lsprof module.