How do I use cProfile in Python with Fluidity?

Created by Tim Greaves
Keywords:

*** Introduction

This page describes how the Python profiler cProfile can be used in the Python-state-interface in diamond.
More details about the python profilers can be found here: http://docs.python.org/library/profile.html#module-pstats

*** Installing

The python profilers can be installed with

    wajig install python-profiler

*** Using cProfile in the Python-state-interface

The profiler needs to be imported through:

    import cProfile

The profiler works either on a Python script or on Python function. Therefore, in order to profile the python diagnostic, the latter needs to be set in a function. For example, the python diagnostic in diamond becomes:

     def set_my_python_diagnostic():
         field = 1.0
         return field

     field = set_my_python_diagnostic()

The profiler can then be run on the function by typing:

    cProfile.run('set_my_python_diagnostic()', 'output_file')

in the python diagnostic window in diamond. The first argument of cProfile.run refers to the profiled function. The second argument is the name of the file containing the profiler output. Note that the output file is binary. The conversion to ascii can be done by the module pstats as follows.

     import pstats
     s = pstats.Stats('output_file')
     s.print_stats()